2 回答
TA贡献1802条经验 获得超5个赞
您可以使用flatMap它们,并在下一个中使用它的响应,通过使用it参数,这是前一个的响应。
mathApi.multiplyByTwo(1)
.flatMap {
mathApi.multiplyByTwo(it)
}.flatMap {
mathApi.multiplyByTwo(it)
}.subscribe {
// here "it" will be 4 (1*2*2)
}
如果您不知道flatMap最终会有多少个s,例如,您可以使用递归函数来完成。
private fun multiplyByTwo(number: Int) {
mathApi.multiplyByTwo(number).subscribe {
if (it < Integer.MAX_VALUE) { // When you run out of data.
multiplyByTwo(it)
}
}
}
TA贡献1830条经验 获得超3个赞
您可以使用保存可变状态的 generate 函数:
data class ApiResponse(
val nextPage: Int? = null
)
data class GeneratorState(
var lastResponse: ApiResponse
)
fun makeApiCall(page: Int): ApiResponse {
return ApiResponse(page + 1)
}
Flowable
.generate(
Callable { GeneratorState(makeApiCall(0)) },
BiConsumer { state: GeneratorState, emitter: Emitter<ApiResponse> ->
val latest = state.lastResponse
if (latest.nextPage != null) {
val response = makeApiCall(latest.nextPage)
state.lastResponse = response
emitter.onNext(response)
} else {
emitter.onComplete()
}
})
.subscribe(object : FlowableSubscriber<ApiResponse> {
var subscription: Subscription? = null
override fun onSubscribe(s: Subscription) {
subscription = s
s.request(1)
}
override fun onNext(response: ApiResponse) {
println("onNext :$response")
if (response.nextPage != null && response.nextPage < 10) {
subscription?.request(1)
} else {
subscription?.cancel()
}
}
override fun onComplete() {
println("Completed")
}
override fun onError(t: Throwable) {
t.printStackTrace()
}
})
添加回答
举报