Home > Mobile >  Flatten Combine publisher with an output of [String] to just String
Flatten Combine publisher with an output of [String] to just String

Time:11-04

I have a publisher that has an array as its output, I'd like to change it to shoot out just the value without the array.

// in a playground

import Combine

var subj = PassthroughSubject<[String], Never>()

subj.send(["1", "2", "3"])

// create publisher where Output == String
// if we did PublisherX(subj).eraseToAnyPublisher it'd 
// be of type AnyPublisher<String, Never> 
let cancel = PublisherX(subj).sink {
    // prints
    // "1"
    // "2"
    // "3"
    // rather than
    // ["1", "2", "3"]
}

CodePudding user response:

You can use flatMap and Array.publisher:

var subj = PassthroughSubject<[String], Never>()

subj
  .flatMap(\.publisher)
  .sink {
    print($0)
  }

subj.send(["1", "2", "3"])
  • Related