Skip to content

Instantly share code, notes, and snippets.

@woodycatliu
Last active March 2, 2023 17:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save woodycatliu/5eaa0331a63d631c68402364cc2bdf07 to your computer and use it in GitHub Desktop.
Save woodycatliu/5eaa0331a63d631c68402364cc2bdf07 to your computer and use it in GitHub Desktop.
Dump Streams with Swift Combine

Dump Streams with Swift Combine

When I develop the project in Swift, The Swift.print is the most commonly used.
But some times I wish more readable dectect value like use dump, even if I programming in Combine. So I create the combine extension for dump.

You can use like below.

 publisher
    .dump()
    .sink { ... }
    .store(&bag)
import Foundation
import Combine
extension Publishers {
private class BagContainer {
var bag = Set<AnyCancellable>()
}
public struct Dump<Upstream> : Publisher where Upstream : Publisher {
private var bagContainer = BagContainer()
public typealias Output = Upstream.Output
public typealias Failure = Upstream.Failure
public let upstream: AnyPublisher<Output, Failure>
public let prefix: String
public init<P: Publisher>(_ publisher: P, _ prefix: String = "") where P.Output == Output, P.Failure == Failure {
self.prefix = prefix
self.upstream = publisher.eraseToAnyPublisher()
}
public func receive<S: Combine.Subscriber>(subscriber: S) where S.Input == Output, S.Failure == Failure {
binding(upstream, prefix)
upstream.subscribe(subscriber)
}
private func binding<P: Publisher>(_ publisher: P, _ prefix: String) {
let prefix = prefix.isEmpty ? "" : "\(prefix) "
publisher.sink(receiveCompletion: {
switch $0 {
case .finished:
Swift.print("\(prefix)Finished -----------------")
case .failure(let error):
Swift.print("\(prefix)Error in -----------------")
Swift.dump(error)
Swift.print("\(prefix)Error End -----------------")
}
}, receiveValue: { value in
Swift.print("\(prefix)Value in -----------------")
Swift.dump(value)
Swift.print("\(prefix)Value End -----------------")
}).store(in: &bagContainer.bag)
}
}
}
extension Publisher {
public func dump(_ prefix: String = "") -> Publishers.Dump<Self> {
return Publishers.Dump(self, prefix)
}
public func debugDump(_ prefix: String = "")-> AnyPublisher<Self.Output, Self.Failure> {
#if DEBUG
return dump(prefix).eraseToAnyPublisher()
#else
return AnyPublisher(self)
#endif
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment