在 AnyCancellable 上调用 .cancel() 与制作 AnyCancellable 之间有区别吗? = 在 SwiftUI 中为零?
Is there a difference between calling .cancel() on an AnyCancellable vs. making an AnyCancellable? = nil in SwiftUI?
我在玩 Combine,我意识到不是在 AnyCancellable
上调用 .cancel()
,而是将 AnyCancellable
设为 Optional
并将其设置为 nil
也停止值流。
将 AnyCancellable?
设置为 nil
而不是在 AnyCancellable
上调用 .cancel()
是不是一件坏事?会不会有内存泄漏之类的负面影响?
供参考,这是代码:
class Test: ObservableObject {
var canceller: AnyCancellable?
func start() {
let timerPublisher = Timer
.publish(every: 1, on: .main, in: .common)
.autoconnect()
self.canceller = timerPublisher.sink { date in
print("the date is \(date)")
}
}
func stop1() {
canceller?.cancel()
}
func stop2() {
canceller = nil
}
}
struct ContentView: View {
@ObservedObject var test = Test()
var body: some View {
VStack(spacing: 20) {
Button("Start") {
self.test.start()
}
Button("Stop1") {
self.test.stop1() // Both buttons stop the stream of values
}
Button("Stop2") {
self.test.stop2() // Is there any difference between using this and stop1?
}
}
}
}
从取消的角度来看没有区别
来自苹果的documentation:
An AnyCancellable instance automatically calls cancel() when deinitialized.
Is setting an AnyCancellable? to nil instead of calling .cancel() on an AnyCancellable a bad thing? Does it have any negative consequences such as leaking memory or something?
取消两者是相等的,但从内存管理的角度来看,将 cancellable 设置为 nil 更可取,因为在 cancel()
AnyCancellable 本身仍然存在之后,如果所有者继续存在,这可能会导致一些意想不到的副作用并且活跃并以某种方式引用 AnyCancellable 属性.
所以,我想说,为了安全起见,最好将 AnyCancellable 设置为 nil - 这两种方法都有。
我在玩 Combine,我意识到不是在 AnyCancellable
上调用 .cancel()
,而是将 AnyCancellable
设为 Optional
并将其设置为 nil
也停止值流。
将 AnyCancellable?
设置为 nil
而不是在 AnyCancellable
上调用 .cancel()
是不是一件坏事?会不会有内存泄漏之类的负面影响?
供参考,这是代码:
class Test: ObservableObject {
var canceller: AnyCancellable?
func start() {
let timerPublisher = Timer
.publish(every: 1, on: .main, in: .common)
.autoconnect()
self.canceller = timerPublisher.sink { date in
print("the date is \(date)")
}
}
func stop1() {
canceller?.cancel()
}
func stop2() {
canceller = nil
}
}
struct ContentView: View {
@ObservedObject var test = Test()
var body: some View {
VStack(spacing: 20) {
Button("Start") {
self.test.start()
}
Button("Stop1") {
self.test.stop1() // Both buttons stop the stream of values
}
Button("Stop2") {
self.test.stop2() // Is there any difference between using this and stop1?
}
}
}
}
从取消的角度来看没有区别
来自苹果的documentation:
An AnyCancellable instance automatically calls cancel() when deinitialized.
Is setting an AnyCancellable? to nil instead of calling .cancel() on an AnyCancellable a bad thing? Does it have any negative consequences such as leaking memory or something?
取消两者是相等的,但从内存管理的角度来看,将 cancellable 设置为 nil 更可取,因为在 cancel()
AnyCancellable 本身仍然存在之后,如果所有者继续存在,这可能会导致一些意想不到的副作用并且活跃并以某种方式引用 AnyCancellable 属性.
所以,我想说,为了安全起见,最好将 AnyCancellable 设置为 nil - 这两种方法都有。