在Swift Combine流水线中插入注释。

huangapple go评论54阅读模式
英文:

Insert comment into Swift Combine pipeline

问题

以下是您要求的代码部分的中文翻译:

这是来自我的发布者的一部分代码:

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

如果我想知道何时发生了什么,我可以这样做:

    let cancellable = URLSession.shared.dataTaskPublisher(for: url)
        .map(\.data)
        .map { print("在解码之前"); return $0 }
        .decode([Object].self, decoder: JSONDecoder()
        .map { print("在解码之后"); return $0 }
        .sink(...)

是否有比这个 `map` 或类似的更好的方法?
英文:

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?

答案1

得分: 1

如评论中提到的,明显的答案是.print()操作符。如果您只想查看特定类型事件的打印语句,那么请改用handleEvents

let cancellable = URLSession.shared.dataTaskPublisher(for: url)
    .map(\.data)
    .handleEvents(receiveOutput: { _ in print("在解码之前") })
    .decode(type: [Object].self, decoder: JSONDecoder())
    .handleEvents(receiveOutput: { _ in print("在解码之后") })
    .sink(receiveCompletion: { _ in }, receiveValue: { _ in })

不要翻译代码部分。

英文:

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 })

huangapple
  • 本文由 发表于 2023年2月9日 03:44:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/75390996.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定