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

Viewed 1835

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?

2 Answers

Here is the code:

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

What you probably want to do is to use a FlatMap on the publisher of the Foo array, using a function which converts the Foo array to an Observable of Foo (which is where the from comes in).

.flatMap { $0.publisher }
Related