我正在RX快速问题上工作,以模拟4个用户的点击。需求是让它们异步发生,以响应RX中的其他事件。所以我不能用计时器或时刻表。
我正在考虑一个函数,它可以从一个可以观察到的值中“拉”出最多4个值,然后终止。我的问题是:
是什么操作符允许我“拉”或从一开始就完成一个可以观察到的所有元素?
func recursive(duration: int) -> Observable<Int>
{
// logic that may terminate recursion based on network conditions
//logic to terminate if number of taps exceeded
If I take from the taps array observable, and it completes - terminate recursion
}这样做的目的是在不依赖外部变量的情况下,尝试创建一个“纯”RX实现。我在考虑Zip,但我很难看出它与解决方案的递归性质有什么关系
发布于 2018-08-13 20:03:58
如果我明白你想要什么,几年前我就用承诺做了这样的事情。也许它能帮到你。https://gist.github.com/dtartaglia/2b19e59beaf480535596
下面,我更新了承诺代码以使用Singles:
/**
Repeatedly evaluates a promise producer until a value satisfies the predicate.
`promiseWhile` produces a promise with the supplied `producer` and then waits
for it to resolve. If the resolved value satisfies the predicate then the
returned promise will fulfill. Otherwise, it will produce a new promise. The
method continues to do this until the predicate is satisfied or an error occurs.
- Returns: A promise that is guaranteed to fulfill with a value that satisfies
the predicate, or reject.
*/
func doWhile<T>(pred: @escaping (T) -> Bool, body: @escaping () -> Single<T>, fail: (() -> Single<Void>)? = nil) -> Single<T> {
return Single.create { event in
func loop() {
_ = body().subscribe(onSuccess: { (t) -> Void in
if !pred(t) {
event(SingleEvent.success(t))
}
else {
if let fail = fail {
_ = fail().subscribe(onSuccess: { loop() }, onError: { event(SingleEvent.error($0)) })
}
else {
loop()
}
}
}, onError: {
event(SingleEvent.error($0))
})
}
loop()
return Disposables.create()
}
}我不希望你能够仅仅使用上面的内容,但希望你能从中得到灵感。
https://stackoverflow.com/questions/51828352
复制相似问题