Use RxJava and Retrofit to iterate through list and augment results based on subqueries

前端 未结 3 1956
滥情空心
滥情空心 2021-02-08 07:07

I\'m using retrofit and I feel like rxjava (with retrolambda) would be a good fit for the following flow:

  1. get list of widgets (http)
  2. for each widget

3条回答
  •  再見小時候
    2021-02-08 07:42

    akarnokd's answer is quite helpful but that may cause NetworkOnMainThreadException. To solve that I have added

    .observeOn(AndroidSchedulers.mainThread())
    .subscribeOn(Schedulers.io())
    

    on every requests

    apiService.getWidgets(token)
    .observeOn(AndroidSchedulers.mainThread())      //added this
    .subscribeOn(Schedulers.io())                   //added this
    .flatMapIterable(v -> v)
    .flatMap(w -> 
        apiService.getArticles(token, w.type)
        .observeOn(AndroidSchedulers.mainThread())  //added this
        .subscribeOn(Schedulers.io())               //added this
        .flatMapIterable(a -> a)
        .doOnNext(a -> db.insert(a))
        .doOnNext(a -> {
             w.articleName = a.name;
             w.articleUrl = a.url;
        })
        .takeLast(1)
        .map(a -> w)
    )
    .toList()
    .subscribe(
        modifiedWidgets -> saveWidgets(modifiedWidgets),
        throwable -> processWidgetError(throwable)
    );
    

提交回复
热议问题