![](/img/trans.png)
[英]How should I use a guard statement correctly with RxSwift Singles?
[英]How to chain RxSwift Singles in order
假設我要按順序運行 3 種方法,並且入口點取決於整數(數字)。
func method1() -> Single<Void> {
return .just(())
}
func method2() -> Single<Void> {
return .just(())
}
func method3() -> Single<Void> {
return .just(())
}
在常規 Swift 中會有這樣的開關:
func doThings(startingFrom number: Int) -> Single<Void> {
switch number {
case 0:
method1()
fallthrough
case 1:
method2()
fallthrough
case 2:
method3()
fallthrough
default:
print("Finished")
}
return .just(())
}
但是考慮到 method1()、method2() 和 method3 是 Single 我認為 RxSwift 中應該有一種方法可以將它們鏈接起來而不會弄亂它們的執行順序。
我想過這樣的事情,但這是同步的,因此方法的執行順序沒有保證。
public func doThings(startingFrom number: Int) -> Single<Void> {
var actions: [Single<Void>] = []
switch number {
case 0:
actions.append(method1())
fallthrough
case 1:
actions.append(method2())
fallthrough
case 2:
actions.append(method3())
fallthrough
default:
break
}
return Single
.zip(actions)
.do(onSuccess: { _ in
Log.debug("Finished")
})
.mapToVoid()
}
對不起,如果我沒有意義,我對 RxSwift 很陌生。 如果有問題,請糾正我。
您的解決方案非常接近。 只需使用concat
而不是zip
就可以了。
我的錯,Single 缺少concat
運算符,因此您必須先轉換為 Observable 或 Completable。 這里有幾個選項:
func doThings(startingFrom number: Int) -> Single<Void> {
Observable.concat(
[method1(), method2(), method3()]
.dropFirst(number)
.map { $0.asObservable() }
)
.toArray()
.map(to: ())
.do(onSuccess: { _ in
print("Finished")
})
}
func doThingsʹ(startingFrom number: Int) -> Single<Void> {
Completable.concat(
[method1(), method2(), method3()]
.dropFirst(number)
.map { $0.asCompletable() }
)
.andThen(.just(()))
.do(onSuccess: { _ in
print("Finished")
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.