⏰Timer
⭐️ 注意:Timer 屬於 Foundation 的類別
.onReceive() accepts a publisher as its first parameter and a function to run as its second.
.onChange() is called on the main thread. Avoid performing long-running tasks on the main thread. If you need to perform a long-running task in response to value changing, you should dispatch to a background queue.
Because Timer.TimerPublisher conforms to the ConnectablePublisher protocol, it won’t produce elements until you explicitly connect to it. Do this by either calling connect(), or using an autoconnect() operator to connect automatically when a subscriber attaches.
timer.publish() returns a ConnectablePublisher. It’s a special variant of Publisher that won’t start firing upon subscription until you explicitly call its connect() method. You can also use autoconnect() which automatically connects when the first subscriber subscribes.
👉 Ray ⟩ Combine: Asynchronous Programming with Swift, Ch. 11: Timers
使用 .onReceive() 定義 timer 享有特別的好處:當 view 關閉後,timer 也會自動停止,不用另外呼叫 .invalidate()。若是使用 .sink() 接收 timer 發送的 value 則要處理記憶體的問題。
👉 彼得潘 ⟩ 利用 Combine 產生自動停止的 timer
if you’re OK with your timer having a little float, you can specify some tolerance. This allows iOS to perform energy optimization, because it can fire the timer at any point between its scheduled fire time and its scheduled fire time plus the tolerance you specify. In practice this means the system can perform timer coalescing: it can push back your timer just a little so that it fires at the same time as one or more other timers, which means it can keep the CPU idling more and save battery power.
If you need to keep time strictly then leaving off the tolerance parameter will make your timer as accurate as possible, but please note that even without any tolerance the Timer class is still “best effort” – the system makes no guarantee it will execute precisely.
Ray ⟩ Combine: Asynchronous Programming with Swift, Ch. 11: Timers
Foundation ⟩ Task Management ⟩ Timer (class)
Timer.TimerPublisher (class)
.autoconnect() -> Publishers.Autoconnect
<Timer.TimerPublisher>
Combine ⟩ ConnectablePublisher (protocol) ⟩
.connect() ⭐️ - connects to the publisher, allowing it to produce elements, and returns an instance with which to cancel publishing.
SwiftUI ⟩
Scenes ⟩ ScenePhase (enum)
State ⟩ EnvironmentValues (struct) ⟩ .scenePhase (instance property)
View ⟩ Input and Event Modifiers ⟩
.onReceive(_:perform:) - perform action when emitted data detected.
.onChange(of:perform:) - perform action when specific value changes.
extended in Combine framework.
use @Environment values.
use Timer.TimerPublisher (
ConnectablePublisher) Publisher.use time to do animations.
問:「 What does .autoconnect() do❓ .onReceive(timer) connects the timer to a view automatically❓」
答:「 .autoconnect() automatically connects when the first subscriber subscribes, .onReceive(timer) subscribes to the timer publisher. 」
問:「 What is a RunLoop❓ 」
Last updated