CombineCommunity / CombineExt

CombineExt provides a collection of operators, publishers and utilities for Combine, that are not provided by Apple themselves, but are common in other Reactive Frameworks and standards.
https://combine.community
MIT License
1.73k stars 155 forks source link

How to use WithLatestFrom with @Published #170

Closed hoangtaiki closed 7 months ago

hoangtaiki commented 7 months ago

When I try to use WithLatestFrom with two PassthroughSubject. It works very well.

    let first = PassthroughSubject<Int, Never>()
    let second = PassthroughSubject<String, Never>()
    var cancellables = Set<AnyCancellable>()

    first
        .withLatestFrom(second)
        .sink(receiveCompletion: { print($0) }, receiveValue: { print($0) })
        .store(in: &cancellables)

    first.send(1)
    second.send("one")
    first.send(2)
    second.send("two")

Outputs

one

But if I change second from PassthroughSubject to @Published it will not work

    let first = PassthroughSubject<Int, Never>()
    @Published var second: String = ""

    first
        .withLatestFrom(second.publisher)
        .sink(receiveCompletion: { print($0) }, receiveValue: { print($0) })
        .store(in: &cancellables)

    first.send(1)
    second = "one"
    first.send(2)
    second = "two"

Outputs will be empty

Someone can help/explain for me how to use WithLatestFrom with a @Published?