在Android的RxJava2中结合Singles的最佳方法?

时间:2018-11-25 15:45:42

标签: android reactive-programming rx-java2 rx-android

我是RxJava的新手,想知道是否还有一种更惯用的方式来完成下面显示的方法。

private Flowable<String> fetchTopMovies(Context context, @IntRange(from = 1) int firstPage, @IntRange(from = 1) int lastPage) {
    checkArgument(firstPage > 0, "first page must be at least 1");
    checkArgument(lastPage > 0, "first page must be at least 1");
    checkArgument(lastPage >= firstPage, "last page cannot be less than first page");

    JsonFetcher jsonFetcher = JsonFetcher.getInstance(context);
    Flowable<String> mergedJsonsFlowable = Flowable.empty();

    for (int page = 0; page <= lastPage; page++) {
        String url = "https://api.themoviedb.org/3/movie/top_rated?" +
                "api_key=4&" +
                "language=en-US&" +
                "page=" + page;

        Single<String> jsonSingle = jsonFetcher.fetchJson(url);
        mergedJsonsFlowable = mergedJsonsFlowable.mergeWith(jsonSingle);
    }

    return mergedJsonsFlowable;
}

如您所见,我只是在收集单身人士并将其手工组合成Flowable。是否有一种更好的方式来做到这一点而又不“破坏链条”?

1 个答案:

答案 0 :(得分:0)

我认为您拥有Flowable.range()的完美用例:

private Flowable<String> fetchTopMovies(Context context, @IntRange(from = 1) int firstPage, @IntRange(from = 1) int lastPage) {
   ...
   JsonFetcher jsonFetcher = JsonFetcher.getInstance(context);

   return Flowable.range(0, lastPage)
     .map(i ->  "https://api.themoviedb.org/3/movie/top_rated?" +
       "api_key=4&" +
       "language=en-US&" +
       "page=" + i)
     .flatMapSingle(url -> jsonFetcher.fetchJson(url));
}