gpt4 book ai didi

swift - RxSwift - 处理订阅是否会导致底层序列发出 onComplete?

转载 作者:行者123 更新时间:2023-11-28 07:36:43 25 4
gpt4 key购买 nike

我正在阅读 Packt ( https://www.oreilly.com/library/view/reactive-programming-with/9781787120211/) 撰写的关于 RxSwift 的书“使用 Swift 4 进行响应式编程”。在一节中,这本书说:

"Disposing of a subscription will cause the underlying Observable sequence to emit a completed event and terminate"

但是我发现这个短语是不正确的。这是一个例子:

        let publisher = PublishSubject<Int>() //Create an <Int> sequence
let subscription1 = publisher.asObservable() //Create 1st subscription
.debug("Subscription 1")
.subscribe { (event) in
print(event)
}
let subscription2 = publisher.asObservable() //Create 2nd subscription
.debug("Subscription 2")
.subscribe { (event) in
print(event)
}
publisher.onNext(1) //Emit first event
subscription1.dispose() //Dispose the 1st subscription. According to the phrase above, publisher should emit an onComplete event
publisher.onNext(2) //Emit second event

正如我在代码中的评论所说,在 subscription1.dispose() 处,publisher 应该发出 onComplete 事件,但实际上它仍然可以发出新事件像往常一样,因此输出:

2018-11-01 19:43:59.796: Subscription 1 -> subscribed
2018-11-01 19:43:59.798: Subscription 2 -> subscribed
2018-11-01 19:43:59.798: Subscription 1 -> Event next(1)
next(1)
2018-11-01 19:43:59.798: Subscription 2 -> Event next(1)
next(1)
2018-11-01 19:43:59.799: Subscription 1 -> isDisposed
2018-11-01 19:43:59.799: Subscription 2 -> Event next(2)
next(2)

谁能证实我的理解是正确的?还是我错过了 RxSwift 幕后的任何东西?

提前致谢

最佳答案

您对取消订阅的理解是正确的:处理订阅不会导致 onComplete 运行。但是,当达到 onComplete 或 onError 时,它将自动取消订阅(http://reactivex.io/documentation/contract.html 订阅和取消订阅部分非常有用)

关于swift - RxSwift - 处理订阅是否会导致底层序列发出 onComplete?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53101662/

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