抱歉措辭尷尬。看下面的例子可能會回答你所有的問題。
所以場景是我想觀察一個值流并收集所有值,直到我看到一個值。但我也希望將我所見證的價值添加到收藏中。
因此,在示例中,我顯示我缺少值“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
*/
uj5u.com熱心網友回復:
您可以使用scan和first(where:):
let cancel = subj
.scan([String]()) { $0 [$1] }
.first { $0.last == "LastPage" }
.sink {
print("complete: \($0)")
} receiveValue: {
print("received: \($0)")
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/517743.html
標籤:迅速结合字首玻璃钢搜集
