很抱歉措辞不得体。看到下面的例子可能会回答你所有的问题。
因此,场景是,我希望观察一个值流,并收集所有值,直到我看到一个值。但我也希望我亲眼目睹的价值能被添加到同事身上。
因此,在这个例子中,我显示我缺少值"lastPage">
我在XCode 13.4.1 的一个操场上做了这个
import Foundation
import Combine
var subj = PassthroughSubject<String, Never>()
let cancel = subj.prefix{
$0 != "LastPage"
}
.collect(.byTime(DispatchQueue(label: "Test"), .seconds(3)))
.sink {
print("complete: ($0)")
} receiveValue: {
print("received: ($0)")
}
print("start")
let strings = [
"!@#$",
"ZXCV",
"LastPage",
"ASDF",
"JKL:"
]
for i in (0..<strings.count) {
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(i)) {
let s = strings[i]
print("sending (s)")
subj.send(s)
}
}
/* this prints the following
start
sending !@#$
sending ZXCV
sending LastPage
received: ["!@#$", "ZXCV"] <<<< I want this array to include 'LastPage'
complete: finished
sending ASDF
*/
您可以使用scan
和first(where:)
:
let cancel = subj
.scan([String]()) { $0 + [$1] }
.first { $0.last == "LastPage" }
.sink {
print("complete: ($0)")
} receiveValue: {
print("received: ($0)")
}