Skip to content

Instantly share code, notes, and snippets.

@funway
Created August 4, 2020 02:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save funway/400a7b760348e7cf2978ddda1963868b to your computer and use it in GitHub Desktop.
Save funway/400a7b760348e7cf2978ddda1963868b to your computer and use it in GitHub Desktop.
TimerPublisher conflict with NSWindow.willCloseNotification
import SwiftUI
struct TimerTest: View {
@State var showSubView = false
@State var date1 = Date()
@State var timer1 = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
weak var myWindow: NSWindow?
// In AppDelegate.swift, use "let contentView = TimerTest(myWindow: window)"
var body: some View {
ZStack{
VStack {
Text("date1: \(date1)")
// If I only use this TimerPublisher, it will auto stop when window closed.
.onReceive(timer1) { currentTime in
self.date1 = currentTime
NSLog("🔴 timer1 trigger")
}
// But if I open this comment, the timer1 will not auto stop.
// .onReceive(NotificationCenter.default.publisher(for: NSWindow.willCloseNotification, object: myWindow)) { _ in
// NSLog("💚 window will close.")
// NSLog("But the timer1 will not auto stop. why?")
// }
// It seems like myWindow's close notification be cut off, not pass through to the TimerPublisher.
// (Sorry I'm not familiar with combine mechanism)
// If I use Asperi's solution (https://stackoverflow.com/a/63232013/5777080) replace the myWindow property
// The timer1 will auto stop agin.
// I'm confused with the difference between the myWindow proterty and that myWindow Environment key
}
}
.frame(width: 500, height: 300)
}
}
@funway
Copy link
Author

funway commented Aug 4, 2020

我又接近一点真相了,如果打开了第二个 onReceive。 其中新建的 Publisher 实例就会有一个指向 myWindow 的强引用啊,(虽然myWindow 在当前 View 中定义的是弱引用。 )这就导致了即使关闭了窗口,myWindow 实例也还有一个引用计数在,不会被销毁 =。=# 那么窗口内的视图 View 自然也不会被销毁。视图不被销毁,那这个订阅关系就还存在,所以 Timer 也就一直运行了。。。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment