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

好久不见. 提交于 2019-12-11 05:59:12

问题


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?


回答1:


Here is the code:

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



回答2:


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).



来源:https://stackoverflow.com/questions/58364436/swift-combine-how-can-i-convert-anypublisherfoo-to-anypublisherfoo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!