[英]How to call rest apis async and wait untill all calls are done in rx-android
In an activity i need to call 4 rest API. 在一个活动中,我需要调用4个rest API。 One API does not depends on another.
一个API不依赖于另一个。 But for a calculation I need data of all 4 APIs.
但是为了进行计算,我需要所有4个API的数据。 So, I'm planning to call APIs asynchronous but wait until all API are done loading.
因此,我打算异步调用API,但要等到所有API完成加载后再调用。 I'm using RxAndroid with retrofit.
我正在使用RxAndroid进行改造。 I don't know how to achieve this using rx.
我不知道如何使用rx实现此目的。 I don't want to use a Boolean for each API call to track if it loaded or not.
我不想为每个API调用使用布尔值来跟踪它是否已加载。 Is there any rx way?
有什么RX方法吗?
For now, I synchronize all calls like below 现在,我将所有呼叫同步如下
Sample code: 样例代码:
fun getData() {
val disposable = dataSource.getLivePayments()
.subscribeOn(schedulerProvider.io())
.observeOn(schedulerProvider.ui())
.subscribe(({ livePayments: List<Payment> ->
this.livePayments.clear()
this.livePayments.addAll(livePayments)
dataSource.getLiveRemittances()
.subscribeOn(schedulerProvider.io())
.observeOn(schedulerProvider.ui())
.subscribe(({ liveRemittances: List<Remittance> ->
this.liveRemittances.clear()
this.liveRemittances.addAll(liveRemittances)
// similarly called dataSource.getLiveTimeSheets()
// and dataSource.getArchiveTimeSheets()
// synchronous
// then call
calculateAmount()
}), ({ t -> this.parseError(t) }))
}), ({ t -> this.parseError(t) }))
compositeDisposable.add(disposable)
}
fun calculateAmount() {
val balance = if(liveRemittances.isNotEmpty()) {
(sum(payment.amount) - sum(timesheet.amount)) * sum(liveRemittance.amount)
} else {
(sum(payment.amount) - sum(timesheet.amount))
}
}
NB: In this procedure, if some API fails, it stop executing next API but i want it should call next API. 注意:在此过程中,如果某些API失败,它将停止执行下一个API,但我希望它应调用下一个API。
If all the API calls are independent you can use the zip
operator: 如果所有API调用都是独立的,则可以使用
zip
运算符:
Single.zip(single1, single2, ..., (result1, result2, ... -> (combine the results)})
If the have dependant results you can use flatMap
如果有依赖结果,则可以使用
flatMap
single1.flatMap(result -> (generate a new Single based on that result)})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.