如何在收到特定值后让 Combine 订阅者完成

How to have Combine subscriber finish upon receiving specific value

我正在尝试使用 Combine 订阅者等待来自发布者的特定值,如果我处理 sink(receiveValue:) 中的值,这似乎很容易,但我想将发布者转换为另一个发布者收到特定值时才结束。

这是有效的代码:

let publisher: AnyPublisher<Int, Never> = ...

let cancellable = publisher.sink(receiveValue: { value in
    if value == myFavoriteNumber {
        // we're finished!
    }
})

我想要完成的是这样的:

let modifiedPublisher: AnyPublisher<Never, Never> = publisher.compactMap({ 
    [=11=] == myFavoriteNumber ? Publishers.Completion.finished : nil 
}).eraseToAnyPublisher()

有办法吗?

我想出的解决方案使用 tryPrefix 运算符:

let FavoriteNumber = 42
let publisher: AnyPublisher<Int, Never> = (0...360).publisher.eraseToAnyPublisher()

let upToFavoriteNum = publisher.tryPrefix {
    [=10=] != FavoriteNumber
}

let subscription = upToFavoriteNum.sink(receiveCompletion: {
    completion in
    debugPrint(completion)
}, receiveValue: {
    print("processing \([=10=])")
})