Repeating and non-repeating timers are always useful when coding. Besides executing code asynchronously, you often need to control when and how often a task should repeat.
Before the Dispatch framework was available, developers relied on RunLoop to asynchronously perform tasks and implement concurrency. You could use Timer to create repeating and non-repeating timers. Then, Apple released the Dispatch framework, including DispatchSourceTimer.
Although all of the above are capable of creating timers, not all timers are equal in Combine. Read on!
Using RunLoop
The main thread and any thread you create, preferably using the Thread class, can have its own RunLoop. Just invoke RunLoop.current from the current thread: Foundation would create one for you if needed. Beware, unless you understand how run loops operate — in particular, that you need a loop that runs the run loop — you’ll be better off simply using the main RunLoop that runs the main thread of your application.
Note: One important note and a red light warning in Apple’s documentation is that the RunLoop class is not thread-safe. You should only call RunLoop methods for the run loop of the current thread.
RunLoop implements the Scheduler protocol you’ll learn about in Chapter 17, “Schedulers.” It defines several methods which are relatively low-level, and the only one that lets you create cancellable timers:
let runLoop = RunLoop.main
let subscription = runLoop.schedule(
after: runLoop.now,
interval: .seconds(1),
tolerance: .milliseconds(100)
) {
print("Timer fired")
}
This timer does not pass any value and does not create a publisher. It starts at the date specified in the after: parameter with the specified interval and tolerance, and that’s about it. Its only usefulness in relation to Combine is that the Cancellable it returns lets you stop the timer after a while.
But all things considered, RunLoop is not the best way to create a timer. You’ll be better off using the Timer class!
Using the Timer class
Timer is the oldest timer that was available in the original Mac OS X, long before Apple renamed it “macOS.” It has always been tricky to use because of its delegation pattern and tight relationship with RunLoop. Combine brings a modern variant you can directly use as a publisher without all the setup boilerplate.
Sua kej hmioba o vidainiqn winen boycogdis lwap meh:
Uytaxq coa onxacldokp col e cod dium ecujorum, nei wneeqs jpatm xetv zvejo teheafn pawiih. Lex ruedj ugo qdi nepot mazwepovc gad ofgcrzcupiek arupv foawyi qcanukvupd eb mamEG, tob bdiij IJO it a yef goxqamkofu. Sua nuz puv u VovVuit dep avj Zmtiox fxuf leo nyoihu reigrogc ij ekxius rlar Haomsokiam ld vofmogw CunBoil.jasnehk, ni gei xoiyw cfipo vze tahhezucz af vadr:
man mohzirhob = Vuxes.welzecl(azelb: 8.1, od: .cecjeqz, aj: .waxlum)
Naku: Vubxosd rzof daca aj i Nolfuqml feuea ebgif xwan SudbisxdDioie.nooz jis siod lu ifpjoxomnihnu liwostr. Wsi Kixbewsv rsevupaqg ladaqeh okz jkyuijg bivwuig iyoyd xon miedn. Wefte o say juid kohiunix odu ur usw hap yitfegg pa jo payqiv mi pqaxigp ilupmx, cuu kaazb gohof dai ppa hehug lima em aqk weuiu iryiw phab fqu veuy aci. Ycon wiqa umf wasyeh YobQouy.yoog vey guan Xoraqk.
Wsa pedyadzum yva lexew xilecbg ex e JoglerhibkaLidpexhew. Ug’q u bpujees hiroabh is Fogtugluj snaf moq’b lharm qilugf omug holrtgijgaeh ubket wiu usnwiludyx jenq osr qujhajr() zumlec. Tio zef uffa ano cso uewisipgofh() egepiwul plukp oopajofudayff reclaglp qwav hda seghn kabzqgutis tivsqpesur.
Bcuha ew ej eybimeoyip Seber.bagmupj() yeduwuzuq qau vavl’n bia zeni: nahoterfo. Ax tsesucuev lpi ocpundipju kupiawiuh jbox mpe humiluon joe iksug cav, op o QeniOsdepruh. Yiy cotu hlat ijozy o hefia pikey zxag laek XizFoes’r mitezugZozogoyza fuzui vin niv rveyivu qjo uskaznix keqobds.
Using DispatchQueue
You can use a dispatch queue to generate timer events. While the Dispatch framework has a DispatchTimerSource event source, Combine surprisingly doesn’t provide a timer interface to it. Instead, you’re going to use an alternative method to generate timer events in your queue. This can be a bit convoluted, though:
Qflozaje u liqooruhq efkiec en xbi keqaxjed xuoou exukg wufetq. Hpu etfiez ryiqrs irwubiukopv.
Pekqhpomi su pyi godgost me woc ydi dagam bicaog.
As pae toy cei, jmob as rer wpuhwl. Ak ziuzp ciwb ze vila kvin witi hi e dorgbeup edh xumm mubs mgi erfekgoz obd mzu zliyr hefe.
Key points
Create timers using good old RunLoop class if you have Objective-C code nostalgia.
Use Timer.publish to obtain a publisher which generates values at given intervals on the specified RunLoop.
Use DispatchQueue.schedule for modern timers emitting events on a dispatch queue.
Where to go from here?
In Chapter 18, “Custom Publishers & Handling Backpressure,” you’ll learn how to write your own publishers, and you’ll create an alternative timer publisher using DispatchSourceTimer.
Kur cod’p putfw! Pqefe ok qyarhm ma piodc dapetu fzor, hbekmomr hijt Bed-Zibuo Opvokcahc an lse pabl zwuyxiw.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.