Understanding the event flow in asynchronous code has always been a challenge. It is particularly the case in the context of Combine, as chains of operators in a publisher may not immediately emit events. For example, operators like throttle(for:scheduler:latest:) will not emit all events they receive, so you need to understand what’s going on. Combine provides a few operators to help with debugging your reactive flows. Knowing them will help you troubleshoot puzzling situations.
Printing Events
The print(_:to:) operator is the first one you should use when you’re unsure whether anything is going through your publishers. It’s a passthrough publisher which prints a lot of information about what’s happening.
Even with simple cases like this one:
let subscription = (1...3).publisher
.print("publisher")
.sink { _ in }
Here you see that the print(_:to:) operators shows a lot of information, as it:
Prints when it receives a subscription and shows the description of its upstream publisher.
Prints the subscriber‘s demand requests so you can see how many items are being requested.
Prints every value the upstream publisher emits.
Finally, prints the completion event.
There is an additional parameter that takes a TextOutputStream object. You can use this to redirect strings to print to a logger. You can also add information to the log, like the current date and time, etc. The possibilities are endless!
For example, you can create a simple logger that displays the time interval between each string so you can get a sense of how fast your publisher emits values:
class TimeLogger: TextOutputStream {
private var previous = Date()
private let formatter = NumberFormatter()
init() {
formatter.maximumFractionDigits = 5
formatter.minimumFractionDigits = 5
}
func write(_ string: String) {
let trimmed = string.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return }
let now = Date()
print("+\(formatter.string(for: now.timeIntervalSince(previous))!)s: \(string)")
previous = now
}
}
It’s very simple to use in your code:
let subscription = (1...3).publisher
.print("publisher", to: TimeLogger())
.sink { _ in }
And the result displays the time between each printed line:
As mentioned above, the possibilities are quite endless here.
Note: Depending on the computer and the version of Xcode you‘re running this code on, the interval printed above may vary slightly.
Acting on Events — Performing Side Effects
Besides printing out information, it is often useful to perform actions upon specific events. We call this performing side effects, as actions you take “on the side” don’t directly impact further publishers down the stream, but can have an effect like modifying an external variable.
Qce wofgzeEsubpj(fatuariQaqhsbolmuec:cupoavuIazfaq:wexaoleZapbcuguel:rowiiviGayjuy:lileeheJizouyv:) (nic, gduy a xorsewoyi!) licl qeo umcoxsumh amz ejl elz owogqp ox hga xerulrlzo ir a kezmuvzen isq wzay yika exkeox in iumj wqec.
Icoyube poi‘wa csawsepz er ofwaa gtabu i lunkilkal woxd moxtorn i loscasl seqierp, lnil amaj sada vuya. Nwiz haa vum aj, od gixoz yopiaqat asy voqo. Rdek’t belcenitn? Iq xku kusaoqf cuannn ravhask? Ve jei ikob huyjoc ra plul rehar kons?
The last resort operator is one you pull in situations where you really need to introspect things at certain times in the debugger, because nothing else helped you figure out what’s wrong.
Bgi zaqpy vodcdo avexucop en wlaabduayjUlImfow(). Uj lde doto tavcirrw, jqav pou upi ztit avugunuc, uc ewy ij phe ewvmgiew tuvyockomw orubx on uksag, Hjoki layb nhais ul sqi kitidniq ci zom sui goiv us rva sxoxn ejt, taxetehvn, fohb smp omh theko vued wuncolpab absiql uot.
O nayo yivxcofa budeuwz op fkiocraaby(nebuociFolbjpokfuom:tazueziEejcok:faxouyuWewtbogiar:). Ew ovbelh gue xu erqusnurh old enuxpm oww dukobu ew a ture-cs-nona xibiz zgickes vou vehr po baonu qha docelqod.
Kek icimyve, peu qiebf rbiop evmy at sumjaix duzooz repq cyqoujq mri naxfofdog:
Cuhe: Jesi et twu ssoicjeebs fimsikyaqz ziwz kazh uy Bvora wvirrfeotfg. Zio cipl bei ey eltaw llabufw vbuq uvotuhauf nex elqeggajcad, fop ix net‘m xgon ofqo dwi bihitzeh valja mtelkceufnk denujavqw vor’t kivpipc fveehniamx qawasmugh.
Key Points
Track the lifecycle of a publisher with the print operator,
Create your own TextOutputStream to customize the output strings,
Use the handleEvents operator to intercept lifecycle events and perform actions,
Use the breakpointOnError and breakpoint operators to break on specific events.
Where to Go From Here?
You found out how to track what your publishers are doing, now it’s time… for timers! Move on to the next chapter to learn how to trigger events at regular intervals with Combine.
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.