RxJava每次执行使用多个可观察(API调用)

时间:2018-10-31 20:22:28

标签: android observable rx-java2 subscriber

我有类似的东西:

private Single<List<Data>> getFirstApiResponse() {
    return Single.just(....)
         /////
         .subscribeOn(Schedulers.io())
         .observeOn(AndroidSchedulers.mainThread());
}

private Single<AnotherData> getSecondApiResponse() {
    return Single.just(....)
         /////
         .subscribeOn(Schedulers.io())
         .observeOn(AndroidSchedulers.mainThread());
}

public void execute() {
    //Here I need to run both observables one by one, and show result of each in View

   // Code exetuting both
   .subscribe(......);
}

如何运行两个可观察对象并在最后一个方法中对其进行订阅。换句话说,我需要运行方法execute,该方法将在每个Observable的UI结果中显示。

顺便说一下,Observable没有连接,它们获取了不同的数据(所以我可以异步运行它们)

2 个答案:

答案 0 :(得分:0)

一种方法是使用flatMap

public void execute() {
    getFirstApiResponse()
            .flatMap(response1 -> {
                // getFirstApiResponse has completed
                // ...
                return getSecondApiResponse();
            })
            .subscribe(response2 -> {
                // getSecondApiResponse has completed
                // ...
            }, error -> {
                // One of the other operation has failed
            });
}

答案 1 :(得分:0)

您也可以根据需要查看zip运算符。此解决方案的缺点是,您不得不将响应组合成对或其他合适的数据结构,这对您来说可能没有意义。

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html [NC,L]

RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [L,R=301]
相关问题