Search code examples
swiftdebuggingoperatorscombine

Insert comment into Swift Combine pipeline


Here is a snippet from my Publisher:

let cancellable = URLSession.shared.dataTaskPublisher(for: url)
    .map(\.data)
    .decode([Object].self, decoder: JSONDecoder()
    .sink(...)

If I want to know what's happening when, I could do this:

let cancellable = URLSession.shared.dataTaskPublisher(for: url)
    .map(\.data)
    .map { print("Before decoding"); return $0 }
    .decode([Object].self, decoder: JSONDecoder()
    .map { print("After decoding"); return $0 }
    .sink(...)

Is there a better way than this (ab)use of map or similar?


Solution

  • As mentioned in the comments, the obvious answer is the .print() operator. If you only want to see print statements for a particular kind of event, then use handleEvents instead.

    let cancellable = URLSession.shared.dataTaskPublisher(for: url)
        .map(\.data)
        .handleEvents(receiveOutput: { _ in print("before decoding") })
        .decode(type: [Object].self, decoder: JSONDecoder())
        .handleEvents(receiveOutput: { _ in print("after decoding") })
        .sink(receiveCompletion: { _ in }, receiveValue: { _ in })