多个Publisher发布者数据流的整合

本小节演示使用CombineLatestMerge将多个Publisher发布者数据流进行整合

示例一:CombineLatest会将发布者最新的数据进行整合

print("Demonstrating CombineLatest")

let usernamePublisher = PassthroughSubject<String, Never>()
let passwordPublisher = PassthroughSubject<String, Never>()

//: 整合最新的数据并进行验证
let validatedCredentialsSubscription = Publishers
    .CombineLatest(usernamePublisher, passwordPublisher)
    .map { (username, password) -> Bool in
        !username.isEmpty && !password.isEmpty && password.count > 12
    }
    .sink { valid in
        print("CombineLatest: are the credentials valid? \(valid)")
    }

//: 输入1次用户名 2次密码 
usernamePublisher.send("avanderlee")
passwordPublisher.send("weakpass")
passwordPublisher.send("verystrongpassword")

输出:

Demonstrating CombineLatest
CombineLatest: are the credentials valid? false
CombineLatest: are the credentials valid? true

示例二:Merge会将多个发布者的数据流合并为一个

print("Demonstrating Merge")
let publisher1 = [1,2,3,4,5].publisher
let publisher2 = [300,400,500].publisher

let mergedPublishersSubscription = Publishers
    .Merge(publisher1, publisher2)
    .sink { value in
        print("Merge: subscription received value \(value)")
}

输出:

Demonstrating Merge
Merge: subscription received value 1
Merge: subscription received value 2
Merge: subscription received value 3
Merge: subscription received value 4
Merge: subscription received value 5
Merge: subscription received value 300
Merge: subscription received value 400
Merge: subscription received value 500

Made with in Shangrao,China By 老雷

Copyright © devler.cn 1987 - Present

赣ICP备19009883号-1