Ilya Mashin
Ilya Mashin

Reputation: 954

Observable<List<SomeItems> from multiple retrofit requests

I get Flowable from retrofit request. I need to get from multiple requests one Object like Observable> in while construction:

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

        Observable<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;
    }

Which operators i need?

Upvotes: 1

Views: 674

Answers (2)

CDilks
CDilks

Reputation: 38

I am going to build off of Maximm Volgin's answer here. (Thank you)

I believe you have multiple observable streams you want to combine into a list of items. I'll break this down into two parts.

  1. Combining the streams into one. This can be accomplished with the zip, merge or flatMap operators depending on order/behaviour Zip Doc Merge Doc FlatMap.

  2. Converting the data from individual items to a list. This can be accomplished with a toList()

I would also suggest not using flowables/Observables for Retrofit calls but Singles instead.

The code will end up looking something along the lines of:

Kotlin:

fun example(): Single<List<CurrencyStamp >> {
    val count = secByDay.div(secByFiveMin)
    return Observable
        .range(0, count)
        .flatMapSingle { curr ->
            // This should be giving you back a Single
            CoinApi.getCompareApi().getCurrencyHistory(symbol, 
                date.getTime() - curr.mul(secByFiveMin),
                convertsSymbols)
        }.toList()
}

Java:

    Single<List<CurrencyStamp>> sample() {
    val count = secByDay / secByFiveMin;
    return Observable
            .range(0, count)
            .flatMapSingle((Function<Integer, SingleSource<String>>) curr -> 
             // This should be giving you back a Single
            CoinApi.getCompareApi().getCurrencyHistory(symbol, 
                date.getTime() - (curr * secByFiveMin),
                convertsSymbols))
            .toList();
}

** Edit: Also you should be handling errors in a stream that can have errors (like a network call) Check out this medium article that talks about it Error handling article

Upvotes: 2

Maxim Volgin
Maxim Volgin

Reputation: 4077

Something like

Observable
  .range(/* */)
  .flatMap (count) -> { CoinApi
    .getCompareApi(/**/)
    .toObservable()
   }
   .toList()

Upvotes: 1

Related Questions