我正在研究RX快速问题,以模拟4个用户点击。要求使它们异步发生以响应RX中的其他事件。所以我不能使用计时器或间隔。
我正在考虑一个函数,该函数将从可观察的对象中“拉出”一个可发出最多4个值然后终止的函数。我的问题是:
什么运算符允许我从头到尾“拉动”或逐步遍历可观察的所有元素?
<ul role="list">
<li role="listitem">
<div><h3 aria-label="item 1">item 1</h3></div>
</li>
<li role="listitem">
<div><h3 aria-label="item 2">item 2</h3></div>
</li>
<li role="listitem">
<div><h3 aria-label="item 2">item 3</h3></div>
</li>
<li role="listitem">
<div><h3 aria-label="item 4">itwem 4</h3></div>
</li>
</ul>
该想法是尝试在不依赖外部变量的情况下实现“纯” RX实现。我正在考虑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
}
,但正在努力查看它与解决方案的递归性质有何关系
答案 0 :(得分:1)
如果我了解您的需求,几年前我使用诺言做了类似的事情。也许可以帮到您。 https://gist.github.com/dtartaglia/2b19e59beaf480535596
下面,我更新了承诺代码以使用Single
:
/**
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()
}
}
我不希望您能够使用上面的内容,但希望您能从中汲取灵感。