PassthroughSubject,本质是把一个数据,变为Publisher
以一个数组publisher为例
let fibonacciPublisher = [0,1,1,2,3,5].publisher
查看fibonacciPublisher(option+鼠标点击),他是Publishers.Sequence<[Int], Never>的类型,是将Sequence转换后的publisher,我们可以用sink的方法,订阅并接收他发布的数据
fibonacciPublisher
.sink(receiveCompletion: { completion in
switch(completion) {
case .finished:
print("finished")
case .failure(let error):
print(error.localizedDescription)
}
}, receiveValue: { value in
print(value)
})
打印结果
0
1
1
2
3
5
finished
结果表明了两个信息:
1、Sequence的数据逐个被发布并接收
2、数据全部发布完毕后,结束了这次订阅
实际应用中,我们很少会用到这种Publisher,我们用到比较多的是PassthroughtSubject 和 CurrentValueSubject
PassthroughSubject
我们用PassthroughSubject发布一个同样的数组
let pubFibonacci = PassthroughSubject<[Int], Never>()
pubFibonacci
.sink(receiveCompletion: { completion in
switch(completion) {
case .finished:
print("finished")
case .failure(l