Recursion iOS RxSwift如何“;拉力”;从(1,2,3)的可观测值?
我正在研究RX swift问题,以模拟4个用户点击。要求它们异步发生,以响应RX中的其他事件。所以我不能使用计时器或时间间隔 我在想一个函数,它可以从一个可以发出最多4个值的可观察对象中“拉”,然后终止。我的问题是: 什么运算符允许我从头到尾“拉动”或逐步遍历可观察对象的所有元素?Recursion iOS RxSwift如何“;拉力”;从(1,2,3)的可观测值?,recursion,ios11,rx-swift,Recursion,Ios11,Rx Swift,我正在研究RX swift问题,以模拟4个用户点击。要求它们异步发生,以响应RX中的其他事件。所以我不能使用计时器或时间间隔 我在想一个函数,它可以从一个可以发出最多4个值的可观察对象中“拉”,然后终止。我的问题是: 什么运算符允许我从头到尾“拉动”或逐步遍历可观察对象的所有元素? func recursive(duration: int) -> Observable<Int> { // logic that may terminate recursion based on n
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
}
func递归(持续时间:int)->可观察
{
//可以根据网络条件终止递归的逻辑
//超过抽头数时终止的逻辑
如果我从可观察的taps数组中获取,它就完成了-终止递归
}
其想法是尝试在不依赖外部变量的情况下实现“纯”RX。我想到了
Zip
,但我很难看出它与解决方案的递归性质有什么关系如果我了解您想要什么,几年前我就用承诺做了类似的事情。也许它能帮助你
下面,我已将承诺代码更新为使用Single
s:
/**
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()
}
}
/**
重复计算承诺生成器,直到值满足谓词。
`promiseWhile`使用提供的'producer'生成承诺,然后等待
让它解决。如果解析值满足谓词,则
回报的承诺将实现。否则,它将产生新的承诺。这个
方法继续执行此操作,直到满足谓词或发生错误为止。
-回报:一种承诺,保证以满足
谓词,或拒绝。
*/
func doWhile(pred:@escaping(T)->Bool,body:@escaping()->Single,fail:(()->Single)?=nil)->Single{
在中返回Single.create{event
func循环(){
_=body().subscribe(onSuccess:{(t)->中的Void
if!pred(t){
事件(SingleEvent.success(t))
}
否则{
如果让失败=失败{
_=fail().subscribe(onSuccess:{loop()},onError:{event(SingleEvent.error($0))})
}
否则{
循环()
}
}
},onError:{
事件(SingleEvent.error($0))
})
}
循环()
返回一次性物品。创建()
}
}
我不希望您能仅仅使用上述内容,但希望您能从中获得灵感。这很像我们试图在RX中实现延时循环,听起来像
示例
运算符。您能绘制一个输入和输出的大理石图吗?然后我们可以计算出函数中的逻辑。