Home > AI > IOS > Combine >

combineLatest(_:)

Example 1:

class Demo11 {
    var cancellables = Set< AnyCancellable>()
    
    func example(of: String) {
        let pub1 = PassthroughSubject<Int, Never>()
        let pub2 = PassthroughSubject<String, Never>()

        pub1
            .combineLatest(pub2)
            .sink(receiveCompletion: { _ in print("Completed") },
                  receiveValue: { print("P1: \($0), P2: \($1)") })
            .store(in: &cancellables)

        pub1.send(1)
        pub1.send(2)

        pub2.send("a")
        pub2.send("b")

        pub1.send(3)

        pub2.send("c")

        pub1.send(completion: .finished)
        pub2.send(completion: .finished)
    }
}


let d = Demo11()
d.example(of: "good")

// P1: 2, P2: a
// P1: 2, P2: b
// P1: 3, P2: b
// P1: 3, P2: c
// Completed

Example 2 (Apple Official)

let pub1 = PassthroughSubject<Int, Never>()
let pub2 = PassthroughSubject<Int, Never>()

cancellable = pub1
    .combineLatest(pub2)
    .sink { print("Result: \($0).") }

pub1.send(2)
pub2.send(2)
pub1.send(3)
pub1.send(45)
pub2.send(22)

// Prints:
//    Result: (2, 2).    // pub1 latest = 2, pub2 latest = 2
//    Result: (3, 2).    // pub1 latest = 3, pub2 latest = 2
//    Result: (45, 2).   // pub1 latest = 45, pub2 latest = 2
//    Result: (45, 22).  // pub1 latest = 45, pub2 latest = 22

Leave a Reply