Operator之多重订阅(Working with multiple subscribers)
多重订阅:一个生成者,多个消费者
multicast
let publisher = ["First", "Second", "Third"]
.publisher
.map {
($0, Int.random(in: 1...100))
}
.print("Random")
.multicast {
PassthroughSubject<(String, Int), Never>()
}
cancellable1 = publisher.sink { print($0) }
cancellable2 = publisher.sink { print($0) }
cancellable3 = publisher.sink { print($0) }
publisher.connect()
打印结果如下:
Random: receive value: (("First", 22))
("First", 22)
("First", 22)
("First", 22)
Random: receive value: (("Second", 82))
("Second", 82)
("Second", 82)
("Second", 82)
Random: receive value: (("Third", 59))
("Third", 59)
("Third", 59)
("Third", 59)
share
share可自动连接,不需要调用.connect
let publisher = ["First", "Second", "Third"]
.publisher
.map {
($0, Int.random(in: 1...100))
}
.print("Random")
.share()
cancellable1 = publisher.sink { print($0) }
cancellable2 = publisher.sink { print($0) }
cancellable3 = publisher.sink { print($0) }
share
是下边代码的极简写法:
.multicast { PassthroughSubject<(String, Int), Never>() }