gpt4 book ai didi

ios - 使用RxSwift Observables进行递归调用

转载 作者:行者123 更新时间:2023-12-01 18:36:01 24 4
gpt4 key购买 nike

我正在尝试使用RxSwift Observables进行递归调用。

import RxSwift

func observeUntil(initialValue: Int) -> Observable<Int> {

return Observable.deferred {
.just(initialValue)
}
.do(onNext: {
print("current item is", $0)
})
.flatMapLatest{ (item) -> Observable<Int> in
if item < 5 {
return Observable.just(item)
// .delay(.seconds(1), scheduler: MainScheduler.instance)
.flatMapLatest{observeUntil(initialValue: $0 + 1)}
} else {
return .just(item)
}
}
}
_ = observeUntil(initialValue: 0)
.subscribe()

当我在上面的代码中 注释延迟时,输出正确显示如下
current item is 0
current item is 1
current item is 2
current item is 3
current item is 4
current item is 5
Program ended with exit code: 0

使用 延迟时,代码仅输出
current item is 0
Program ended with exit code: 0

请帮助我了解添加延迟后会发生什么。

最佳答案

答案与您在其中执行此代码的环境有关。该程序调用observeUntil(initialValue:)函数,然后在该函数返回时立即存在。

如果没有delay,则函数将在递归代码全部执行后返回。使用delay,该函数将在延迟开始时返回。

基本上,您的程序在不到一秒钟的时间内结束,因此仅输出“0”。

关于ios - 使用RxSwift Observables进行递归调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58932895/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com