Ilya Mashin
Ilya Mashin

Reputation: 954

Convert Flowables<Item> to Flowable<List<Item>> or other observable

Which operator should be used to convert many Flowable<CurrencyStamp> to Flowable<List<CurrencyStamp>>?

Conversion code:

public static Single<List<CurrencyStamp>> getStampByDay(String symbol, Date date, String... convertsSymbols){
    long count = 0;

    Single<List<CurrencyStamp>> result = null;
    while (count < secByDay){
        Flowable<CurrencyStamp> item = CoinApi.getCompareApi().getCurrencyHistory(symbol, date.getTime() - count,
                convertsSymbols).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());


        count += secByFiveMin;
    }

    return result;
}

In "while" construction i need added each "item" to "base" and create Single<List<Currency>>(for example) in result

Upvotes: 0

Views: 2150

Answers (2)

Ilya Mashin
Ilya Mashin

Reputation: 954

I write this code:

public static Single<Currencies> getCurrencyFlowable(){

        Single<Currencies> usd = CoinApi.getMarketCupApi().getCurrencies();
        Single<Currencies> rub = CoinApi.getMarketCupApi().getCurrencies("RUB");
        Single<Currencies> eur = CoinApi.getMarketCupApi().getCurrencies("EUR");
        Single<Currencies> btc = CoinApi.getMarketCupApi().getCurrencies("BTC");

        List<Single<Currencies>> singles = new ArrayList<>();
        singles.add(usd);
        singles.add(rub);
        singles.add(eur);
        singles.add(btc);

        return Single.zip(singles, objects -> {
            Currencies[] currencies = new Currencies[objects.length];
            for (int i = 0; i < objects.length; i++) {
                currencies[i] = (Currencies)objects[i];
            }
            return ramming(currencies);
        }).subscribeOn(Schedulers.io() )
                .observeOn(AndroidSchedulers.mainThread());

    }

Work for me.

Upvotes: 0

Sergej Isbrecht
Sergej Isbrecht

Reputation: 4012

In order to convert from Flowable to Flowable> you would Flowable#toList, which will return a Single>

Single<List<Integer>> listSingle = Flowable.just(1, 2, 3).toList();

Just remember, that given Single will return only one value or an error. The collected List will be emitted, when given Flowable completes. OnError in Flowable will be propagated in Single with onError.

Caution: When the Flowable is infinite, you will cause a memory leak, because the List will never be emitted due to no "onComplete" from given Flowable.

Upvotes: 1

Related Questions