Retrofit & RxJava multiple requests complete

后端 未结 4 2247
盖世英雄少女心
盖世英雄少女心 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 11:05

    Well it depends, as always. Do you need to process the returned values down the chain, or just save it?

    In this implementation I use Single and Completable. You subscribe to the completable and you will get notified when both Singles finished.

    @Test
    public void name() throws Exception {
            TestScheduler testScheduler = new TestScheduler();
            Single request1 = Single.timer(1000, TimeUnit.MILLISECONDS, testScheduler)
                    .doOnSuccess(aLong -> {
                        System.out.println("save to db.");
                    });
            Single request2 = Single.timer(500, TimeUnit.MILLISECONDS, testScheduler)
                    .doOnSuccess(aLong -> {
                        System.out.println("save to db.");
                    });
    
            Completable completable = Single.zip(request1, request2, (aLong, aLong2) -> aLong).toCompletable();
    
            TestObserver test = completable.test();
    
            testScheduler.advanceTimeBy(1010, TimeUnit.MILLISECONDS);
    
            test.assertComplete();
    }
    

    You also can use flatMapCompletable instead of doOnSuccess

    @Test
    public void name() throws Exception {
        TestScheduler testScheduler = new TestScheduler();
        Completable request1 = Single.timer(1000, TimeUnit.MILLISECONDS, testScheduler)
                .flatMapCompletable(this::saveToDb);
    
        Completable request2 = Single.timer(500, TimeUnit.MILLISECONDS, testScheduler)
                .flatMapCompletable(this::saveToDb);
    
        // need to cheat here, becuase completeable does not provide zip
        Completable completable = Single.zip(request1.toSingle(() -> 1), request1.toSingle(() -> 1), (aLong, aLong2) -> aLong)
                .toCompletable();
    
        TestObserver test = completable.test();
    
        testScheduler.advanceTimeBy(1010, TimeUnit.MILLISECONDS);
    
        test.assertComplete();
    }
    
    private Completable saveToDb(long value) {
        return Completable.complete();
    }
    

提交回复
热议问题