Clément Cardonnel
Clément Cardonnel

Reputation: 5317

How to make combineLatest send a value when one of its publishers haven't emitted yet?

I'm trying to use CombineLatest to publish a value whenever one of two publishers change. It just happens that one of these publishers is an objectWillChange property of an ObservedObject (PassthroughSubject<Void, Never>).

Publishers.CombineLatest(
    settings.objectWillChange,
    $aPublishedProperty)
    .sink(receiveValue: { _, _ in
        // Do something…
    })
    .store(in: &subscriptions)

The issue here is as long as this object don't change, CombineLatest will never emit. And I actually don't care about its void value. I'm just putting it here so that if it ever changes in the future, then my sink will get called again.

How can I trigger CombineLatest without an initial value? i.e: only with the change of aPublishedProperty?

Upvotes: 1

Views: 894

Answers (1)

Cl&#233;ment Cardonnel
Cl&#233;ment Cardonnel

Reputation: 5317

There's a nice operator called prepend(_:) that you can use to make a publisher emit an initial value.

In my case, all I had to do was to add .prepend(()) to objectWillChange.

Publishers.CombineLatest(
    settings.objectWillChange.prepend(()), // ⬅️ Useful stuff here
    $aPublishedProperty)
    .sink(receiveValue: { _, _ in
        // Do something…
    })
    .store(in: &subscriptions)

See it in the docs

Upvotes: 2

Related Questions