โฐ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.
๐ ๐ โฉ Replacing Foundation Timers with Timer Publishers
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.
๐ Paul โฉ Triggering events repeatedly using a timer
Last updated