在一些flatMap链之后,我想在最后使用所有以前的结果,假设我有以下代码:
func getObservable1() -> Observable<API1Response> {
...
}
func getObservable2(param: API1Response) -> Observable<API2Response> {
...
}
func getObservable3(param: API2Response) -> Observable<API3Response> {
...
}
getObservable1()
.flatMap { api1Response in
return getObservable2(api1Response)
}
.flatMap { api2Response in
return getObservable3(api2Response)
}
.subscribe(onNext: { api3Response in
// I want to use both of api1Response and api2Response here
})
我该怎么做?
我应该将api响应保存到范围变量中,然后使用后者吗?
类似的东西:
var api1Response: API1Response?
func getObservable1() -> Observable<API1Response> {
...
self.api1Response = api1Response
...
}
...
getObservable1()
...
.subscribe(onNext: { api3Response in
// use ap1Response here
print(self.api1Response)
})
谢谢!
- - - - - - - - UPDATE
基于@Misternewb的回答,我发布了可运行的代码以供测试。
func getObservable1() -> Observable<Int> {
return Observable.of(1)
}
func getObservable2(num: Int) -> Observable<Int> {
return Observable.of(num + 1)
}
func getObservable3(num: Int) -> Observable<Int> {
return Observable.of(num + 10)
}
getObservable1()
.flatMap { ret1 in
return getObservable2(num: ret1).map { (ret1, $0) }
}
.flatMap { ret1, ret2 in
return getObservable3(num: ret2).map { (ret1, ret2, $0) }
}
.subscribe(onNext: { ret1, ret2, ret3 in
print(ret1)
print(ret2)
print(ret3)
})
输出
1
2
12
答案 0 :(得分:1)
您可以尝试以下方法:
func getObservable1() -> Observable<API1Response> {
return .empty()
}
func getObservable2(_ param: API1Response) -> Observable<API2Response> {
return .empty()
}
func getObservable3(_ param: API2Response) -> Observable<API3Response> {
return .empty()
}
func request() {
getObservable1()
.flatMap { api1Response in
return getObservable2(api1Response).map { (api1Response, $0) }
}
.flatMap { api1Response, api2Response in
return getObservable3(api2Response).map { (api1Response, api2Response, $0) }
}
.subscribe(onNext: { api1Response, api2Response, api3Response in
})
}
答案 1 :(得分:0)
您是否需要此回复处于先决条件顺序,或者您只是需要成功完成所有响应?
如果您需要等待请求#1和请求#2的完成,那么您可以使用
Observable.combineLatest(requestObservable1, requestObservable2)
.flatMap { (requestResult1, requestResult2) -> Observable<You-Data-Type> in
// Use result from request #1 & #2
return requestObserver3
}.subscribe(onNext: { (resultRequest3) in
})
...