I have two publishers, one that gathers messages based on a state, and the second which is a Timer. I want these to fire in order – so first gather data, then start a timer. How can I do this? This is my current code:
let messagesPublisher = OnboardingStateLogic.publisher(
forState: state,
nextState: nextState
)
messagesPublisher
.sink { completion in
print("completed")
} receiveValue: { [weak self] messages in
messages.forEach { message in
self?.queue.enqueue(message)
}
}
timer = Timer
.publish(every: 2, on: .main, in: .default)
.autoconnect()
.sink { _ in
self.dequeueMessages()
}
2
Answers
I ended up using
Publishers.Zip
. This only publishes when both upstream publishers have outputted a value:You can use the
flatMap
operator to transform a publisher or value into a new publisher in the Combine chain. For example:You would replace my trivial
Just(1)
publisher with yourmessagesPublisher