gpt4 book ai didi

swift - RXSwift,检测到重入异常

转载 作者:搜寻专家 更新时间:2023-11-01 06:01:50 24 4
gpt4 key购买 nike

我是 RXSwift 的初学者,我的代码有问题

我有代码:

let dartScore = PublishSubject<Int>()
dartScore.asObservable()
.scan(501) { intermediate, newValue in
let result = intermediate - newValue
return result >= 0 ? result : intermediate
}
.do(onNext: {
if $0 == 0 {
dartScore.onCompleted()
}
})
.subscribe({
print($0.isStopEvent ? $0 : $0.element!)
})
.disposed(by: disposeBag)

dartScore.onNext(13)
dartScore.onNext(50)
dartScore.onNext(60)
dartScore.onNext(378)

我得到错误:

⚠️ Reentrancy anomaly was detected. ⚠️

Debugging: To debug this issue you can set a breakpoint in /****RxSwift/RxSwift/Rx.swift:97 and observe the call stack.

Problem: This behavior is breaking the observable sequence grammar. next (error | completed)? This behavior breaks the grammar because there is overlapping between sequence events. Observable sequence is trying to send an event before sending of previous event has finished.

为什么我不能在 .do(onNext) 中执行“.onCompleted()”,我应该怎么做才能避免警告?

我正在使用 XCode 9.0、swift 4、RXSwift 4.0.0

谢谢

最好的问候

最佳答案

您不能在 .onNext() 中执行 .onCompleted(),因为在那种情况下您会让 observable 吃掉自己的尾部。这也会导致内存循环。

正如@Enigmativity 在评论中建议的那样,您应该使用takeWhile() 来处理这种情况:

dartScore.asObservable()
.scan(501) { intermediate, newValue in
let result = intermediate - newValue
return result >= 0 ? result : intermediate
}
.takeWhile { $0 != 0 }
.subscribe({
print($0.isStopEvent ? $0 : $0.element!)
})

上面的代码产生了一个新的可观察对象,它在值为 0 时完成。

关于swift - RXSwift,检测到重入异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47615027/

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