Retrofit & RxJava multiple requests complete

后端 未结 4 2242
盖世英雄少女心
盖世英雄少女心 2021-02-14 10:25

I need to do:

  1. Request 2 lists of news from different websites
  2. Combine results from requests
  3. Sort items by date
  4. Get 10 newest news
  5. <
4条回答
  •  隐瞒了意图╮
    2021-02-14 10:56

    zip is the way to combine observables. Combining their results is just a consequence.

    If you want to wait for both observables to finish (complete), the easiest way is to use zip. You just don't have to use the results of your requests in the combining function. Just use this function as a way to emit something different when both of those calls finish. When this function emits an item:

    [...] do something when all requests completed (show alert for example)

    For example like this (executing someOtherCall when both of those requests finish):

    Observable obs1 = ...;
    Observable obs2 = ...;
    
    Observable.zip(obs1, obs2, new Func2() {
        @Override
        public String call(Integer integer, Long aLong) {
            return "something completely different";
        }
    }).flatMap(new Func1>() {
        @Override
        public Observable call(String s) {
            return performSomeOtherCall();
        }
    }).subscribe(...);
    

提交回复
热议问题