Search code examples
swiftcombinecombinelatest

CombineLatest in Combine is not fired


let a = Just("a")
let b = Just("b")
_ = Publishers.CombineLatest(a, b).map { a, b in
    print(a, b)
}

This is my simple CombineLatest test. I am calling this method in onAppear function. However, my print(a,b) is not called. How should I fix my code to run print(a, b) ?


Solution

  • A Publisher doesn't produce values until it is given a Subscriber. The map operator isn't a Subscriber.

    The easiest solution (as mentioned by Sajjon) is to use sink:

    let a = Just("a")
    let b = Just("b")
    _ = Publishers.CombineLatest(a, b).sink { a, b in
        print(a, b)
    }
    

    Please note that sink returns an AnyCancellable, and when that AnyCancellable is destroyed, it cancels the subscription. In this example, the _ = means I'm not saving that AnyCancellable, so it is destroyed immediately. That doesn't matter here, because all of the Publishers in this example (the two Justs and the CombineLatest) operate synchronously. They have published everything they will ever publish before the AnyCancellable is destroyed. But in general, you need to save the AnyCancellable if you're subscribing to a Publisher that can publish values asynchronously.