Search code examples
swiftrx-swiftcombine

Swift Combine: How can I convert `AnyPublisher<[Foo], *>` to `AnyPublisher<Foo, *>`?


How can I convert a publisher of array a certain element, to just a publisher of said element (but with more events)?

e.g. how can I convert

AnyPublisher<[Int], Never> to AnyPublisher<Int, Never>?

I think maybe what RxSwift offers with its from operator is similar to what I want to do.

I guess I want the inverse of Combine collect?


Solution

  • Here is the code:

    func example(publisher: AnyPublisher<[Foo], Never>) -> AnyPublisher<Foo, Never> {
        return publisher
            .map { $0.publisher }
            .switchToLatest()
            .eraseToAnyPublisher()
    }