[转] Combine学习笔记 - Combining publishers

参考链接: https://github.com/AvdLee/CombineSwiftPlayground

4天前 7次点击 来自 移动端

标签: Swift

Combining publishers

Several operators let you combine multiple publishers together

CombineLatest

  • combines values from multiple publishers
  • ... waits for each to have delivered at least one value
  • ... then calls your closure to produce a combined value
  • ... and calls it again every time any of the publishers emits a value
print("* Demonstrating CombineLatest")

//: **simulate** input from text fields with subjects
let usernamePublisher = PassthroughSubject<String, Never>()
let passwordPublisher = PassthroughSubject<String, Never>()

//: **combine** the latest value of each input to compute a validation
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)")
    }

//: Example: simulate typing a username and the password twice
usernamePublisher.send("avanderlee")
passwordPublisher.send("weakpass")
passwordPublisher.send("verystrongpassword")

第一个例子是用户名与密码验证,订阅者只消费2个发布者最新的数据

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

前提是,必须2个发布者都有数据产生,例如如果你注释掉passwordPublisher将不会触发sink函数

//: Example: simulate typing a username and the password twice
usernamePublisher.send("avanderlee")
//passwordPublisher.send("weakpass")
//passwordPublisher.send("verystrongpassword")

Merge

  • merges multiple publishers value streams into one
  • ... values order depends on the absolute order of emission amongs all merged publishers
  • ... all publishers must be of the same type.
print("\n* 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)")
}

将2个相同数据类型的发布者合并为1个

* 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 Devler.

Copyright © Devler 2012 - 2022

赣ICP备19009883号-1