Combine's `print` operator
This is a really useful little operator for debugging Combine code. It logs each event in your stream, and adds your given prefix to it as well. The example in Apple's docs) is a good one:
let integers = (1...2)
cancellable = integers.publisher
.print("Logged a message", to: nil)
.sink { _ in }
// Prints:
// Logged a message: receive subscription: (1...2)
// Logged a message: request unlimited
// Logged a message: receive value: (1)
// Logged a message: receive value: (2)
// Logged a message: receive finished
Or you can really simplify it, because both properties are optional. The String is a prefix for the log statement, which is nice because it makes it easy to search your output and to get context if you have multiple Combine streams. But you don't need it. And the second parameter is an output stream, which is just the console by default.
Here's how it looks when you just quickly want to throw a print
in there:
let integers = (1...2)
cancellable = integers.publisher
.print()
.sink { _ in }
// Prints:
// receive subscription: (1...2)
// request unlimited
// receive value: (1)
// receive value: (2)
// receive finished
Aside: I've slightly changed the example from Apple's docs
Amusingly, the commented output is slightly wrong on the docs. Clearly the range in the example was updated from 1..<2
to 1...2
, because the first line of the output is wrong, and it's missing the second receive value
line. A good example of what happens when you change the code and forget to update the docs!
Here's the original. Notice the difference between the ranges in the code and the comment, and the missing second receive value
line compared to my output:
let integers = (1...2)
cancellable = integers.publisher
.print("Logged a message", to: nil)
.sink { _ in }
// Prints:
// Logged a message: receive subscription: (1..<2)
// Logged a message: request unlimited
// Logged a message: receive value: (1)
// Logged a message: receive finished
Published on 30 May 2023