Here's one way to do it, you:
- convert a single array into a pipeline of individual elements with
Publishers.Sequence - Process the elements individually.
- Convert the elements back to an array with the
collect operator.
Here's a contrived example that you can run in an Xcode playground:
import Combine import UIKit class MyStore: ObservableObject { @Published var favorites: [(id: Int, title: String)] = [] let articles = [ (id: 22, title: "foo"), (id: 5, title: "bar"), (id: 13, title: "baz"), ] var cancellable: Set<AnyCancellable> = [] func addFavorites(favorites: AnyPublisher<[Int], Never>) { let articles = self.articles favorites .flatMap(Publishers.Sequence.init) .compactMap { fav in articles.first { fav == $0.id }} .collect() .assign(to: \.favorites, on: self) .store(in: &cancellable) } } let store = MyStore() store.addFavorites(favorites: Just([22, 13]).eraseToAnyPublisher()) print(store.favorites) // => [(id: 22, title: "foo"), (id: 13, title: "baz")]
... however I suspect this isn't actually what you want. A more elegant solution might be to create a bespoke compactMapEach operator. Here's what that looks like:
extension Publisher { public func compactMapEach<T, U>(_ transform: @escaping (T) -> U?) -> Publishers.Map<Self, [U]> where Output == [T] { return map { $0.compactMap(transform) } } }
favoritesis a[[String]], and you're mapping this into[[Article]], and then assign it back tofavorites? (How is that possible? What type isfavorites?) I usually try to demonstrate these usingJustso I can show the entire flow. What's the input and output types?favorites: [String]to[Article]in one flatting closure, but not sure if it's possible without a custom operator.