Search code examples
combine

Is there a way to "forward" a Publisher through a Subject other than `sink`?


I.e. something equivalent to

extension Publisher {
  func send(_ subject: some Subject<Output, Failure>) -> AnyCancellable {
    sink(
      receiveCompletion: subject.send,
      receiveValue: subject.send
    )
  }
}

Solution

  • There is a subscribe(_:) method which does that.

    Here is an example:

    private let originalSubject = PassthroughSubject<Void, Never>()
    private let myRepublishingSubject = PassthroughSubject<Void, Never>()
    private var cancellables: Set<AnyCancellable> = []
    
    originalSubject
       .subscribe(myRepublishingSubject)
       .store(in: &cancellables)
            
    myRepublishingSubject
       .sink {
          print("Republished")
       }
       .store(in: &cancellables)
    
    originalSubject.send()
    

    Replace originalSubject with your publisher.

    However, this is probably not the best way to use Combine in your code, because Subjects are mostly used as a glue between imperative code and Combine code. Why can't you use the original Publisher directly?