Swift 合并共享运算符不起作用?

Swift Combine share operator not working?

我正在尝试共享一个序列的输出。为什么我在添加 share 运算符后在第二个订阅中没有任何值?

import Combine

var cancellables = Set<AnyCancellable>()

let test = [1,2,3].publisher.print().share()

test.sink { value in
    print("Go")
}.store(in: &cancellables)

test.sink { value in
    print("no go ?")
}.store(in: &cancellables)

输出为:

receive subscription: ([1, 2, 3])
request unlimited
receive value: (1)
Go
receive value: (2)
Go
receive value: (3)
Go
receive finished

正是因为您使用了 share() - 它将发布者转换为对共享发布者实例的引用。因此,您的第一个订阅者请求所有可用的东西,发布者生成三个事件并完成(因为它实际上是一次生成发布者)。你的第二个订阅者是通过引用附加到已经完成的共享发布者的,所以你什么也没看到。

只是选择了不太方便的发布者来调查这个运营商。

以下内容应该会有帮助:

    var cancellables = Set<AnyCancellable>()

    let source = PassthroughSubject<Int, Never>()
    let test = source.print().share()

    test.sink { value in
        print("Go")
    }.store(in: &cancellables)

    test.sink { value in
        print("no go ?")
    }.store(in: &cancellables)

    _ = [1,2,3].map { source.send([=10=]) }
request unlimited
receive value: (1)
Go
no go ?
receive value: (2)
Go
no go ?
receive value: (3)
Go
no go ?
receive cancel