英文:
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 })
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论