[转] Combine学习笔记 - Subjects

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

4个月前 126次点击 来自 移动端

标签: Swift

Subjects

  • A subject is a publisher ...
  • ... relays values it receives from other publishers ...
  • ... can be manually fed with new values
  • ... subjects as also subscribers, and can be used with subscribe(_:)

Subjects 是一种遵循 Subject 协议的特殊的发布者。这个协议要求 subjects 有一个 .send(_:) 方法,来允许开发者发送特定的值给订阅者或管道。

Combine 中有两种内建的 subject : CurrentValueSubjectPassthroughSubject。 它们的行为类似,但不同的是 CurrentValueSubject 需要一个初始值并记住它当前的值,PassthroughSubject 则不会。 当调用 .send() 时,两者都将向它们的订阅者提供更新的值。

Example 1

Using a subject to relay values to subscribers

let relay = PassthroughSubject<String, Never>()
relay.send("Hello")
relay.send("World!")
let subscription = relay
	.sink { value in
		print("subscription1 received value: \(value)")
}

What happens if you send "hello" before setting up the subscription?
如上例,在建立订阅者之前调用 .send() 发送的值无法被消费。

修改如下

let relay = PassthroughSubject<String, Never>()

let subscription = relay
	.sink { value in
		print("subscription1 received value: \(value)")
}

relay.send("Hello")
relay.send("World!")

结果:

subscription1 received value: Hello
subscription1 received value: World!

Example 2

Subscribing a subject to a publisher

定义Subject与订阅者,消息的发送由Publisher驱动,这种调用方式笔者认为Subject的角色更像一个消息中介

let relay = PassthroughSubject<String, Never>()
let subscription = relay
    .sink { value in
        print("subscription1 received value: \(value)")
}
let publisher = ["Here","we","go!"].publisher

publisher.subscribe(relay)

Example 3

Using a CurrentValueSubject to hold and relay the latest value to new subscribers

let variable = CurrentValueSubject<String, Never>("")

variable.send("Initial text")

let subscription2 = variable.sink { value in
	print("subscription2 received value: \(value)")
}

variable.send("More text")

先看输出结果:

subscription2 received value: Initial text
subscription2 received value: More text

CurrentValueSubjectPassthroughSubject 最大的不同就是 hold,它会记住所有发送的值,新的订阅者来了,有啥给啥

Made with in Shangrao,China By Devler.

Copyright © Devler 2012 - 2022

赣ICP备19009883号-1