Skip to content

Instantly share code, notes, and snippets.

@funway
Last active August 5, 2020 03:32
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/f88e80b93674bbb0fa83d080cf685476 to your computer and use it in GitHub Desktop.
Save funway/f88e80b93674bbb0fa83d080cf685476 to your computer and use it in GitHub Desktop.
Test of TimerPublisher in SwiftUI
import SwiftUI
struct TimerTest: View {
@State var date = Date()
@State var showSubView = false
@State var timer: Timer?
@State var date1 = Date()
@State var timer1 = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
var body: some View {
ZStack{
if showSubView {
VStack {
Text(" Timer Stoped?")
Button("Back") {
self.showSubView = false
}
}
}
else {
VStack {
Button("Switch to subview"){
self.showSubView = true
}
Text("date: \(date)")
.onAppear(perform: {
self.timer = Timer.scheduledTimer(withTimeInterval: 1,
repeats: true,
block: {_ in
self.date = Date()
NSLog("🔷onAppear timer triggered")
})
})
.onDisappear(perform: {
self.timer?.invalidate()
self.timer = nil
NSLog("🔶 onDisappear stop timer")
// But if I close window, this method never be called
})
Text("date1: \(date1)")
.onReceive(timer1) { currentTime in
self.date1 = currentTime
NSLog("🔴 onReceive timer1 trigger")
}
// In theory, onReceive(timer1) is work well when window close, or just the view disappear
// But, when View switch back from the subview, timer1 won't be resume
// So I have to reinstance a new TimerPubliser onAppear.
.onAppear(perform: {
self.timer1.upstream.connect().cancel()
self.timer1 = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
})
.onDisappear(perform: {
NSLog("🔴 onDisappear timer1 auto stop (only when the view switch, but not called when window closed)")
})
}
}
}
.frame(width: 500, height: 300)
}
}
@funway
Copy link
Author

funway commented Aug 5, 2020

但是我还无法理解 TimerPublisher 怎么做到的自动停止?
按照 apple 的官方文档,Timer 是被 RunLoop 强引用的,生成 TimerPublisher 的时候,就定义了一个 Timer, 通过 on: .main 参数这个 Timer 关联到主线程的 RunLoop。
那 TimerPublisher 它自己呢? 是放在哪里管理? 为什么视图切换,窗口关闭都能引起 TimerPublisher 停止?(可能 Timer 并没有停止,只是 Publisher 停止了)

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