實例方法
zip(_:)
組合來自另一個發布者的元素並將元素對作為元組傳遞。
聲明
func zip<P>(_ other: P) -> Publishers.Zip<Self, P> where P : Publisher, Self.Failure == P.Failure
返回值
從上遊發布者發出元素對作為元組的發布者。
參數
other
另一個發布者。
詳述
使用Publisher/zip(_:)
組合來自兩個發布者的最新元素,並向下遊發出一個元組。返回的發布者等待兩個發布者都發出事件,然後將來自每個發布者的最舊的未使用事件作為元組一起傳遞給訂閱者。
就像一件衣服上的拉鏈或拉鏈將一排排牙齒拉在一起以連接兩側,Publisher/zip(_:)
通過鏈接來自每一側的元素對來組合來自兩個不同發布者的流。
在此示例中,numbers
和 letters
是發出值的 PassthroughSubject
;一旦 Publisher/zip(_:)
從每個接收到一個值,它就會將該對作為一個元組發布給下遊訂閱者。然後它等待下一對值。
let numbersPub = PassthroughSubject<Int, Never>()
let lettersPub = PassthroughSubject<String, Never>()
cancellable = numbersPub
.zip(lettersPub)
.sink { print("\($0)") }
numbersPub.send(1) // numbersPub: 1 lettersPub: zip output: <none>
numbersPub.send(2) // numbersPub: 1,2 lettersPub: zip output: <none>
letters.send("A") // numbers: 1,2 letters:"A" zip output: <none>
numbers.send(3) // numbers: 1,2,3 letters: zip output: (1,"A")
letters.send("B") // numbers: 1,2,3 letters: "B" zip output: (2,"B")
// Prints:
// (1, "A")
// (2, "B")
如果上遊發布者成功完成或失敗並出現錯誤,則壓縮發布者也會這樣做。
可用版本
iOS 13.0+, iPadOS 13.0+, macOS 10.15+, Mac Catalyst 13.0+, tvOS 13.0+, watchOS 6.0+
相關用法
- Swift Optional.Publisher zip(_:_:_:)用法及代碼示例
- Swift Optional.Publisher zip(_:_:_:_:)用法及代碼示例
- Swift Optional.Publisher zip(_:_:)用法及代碼示例
- Swift Optional.Publisher reduce(_:_:)用法及代碼示例
- Swift Optional.Publisher tryDrop(while:)用法及代碼示例
- Swift Optional.Publisher debounce(for:scheduler:options:)用法及代碼示例
- Swift Optional.Publisher breakpoint(receiveSubscription:receiveOutput:receiveCompletion:)用法及代碼示例
- Swift Optional.Publisher mapError(_:)用法及代碼示例
- Swift Optional.Publisher catch(_:)用法及代碼示例
- Swift Optional.Publisher tryAllSatisfy(_:)用法及代碼示例
- Swift Optional.Publisher sink(receiveValue:)用法及代碼示例
- Swift Optional.Publisher scan(_:_:)用法及代碼示例
- Swift Optional.Publisher throttle(for:scheduler:latest:)用法及代碼示例
- Swift Optional.Publisher assertNoFailure(_:file:line:)用法及代碼示例
- Swift Optional.Publisher collect(_:)用法及代碼示例
- Swift Optional.Publisher combineLatest(_:_:_:_:)用法及代碼示例
- Swift Optional.Publisher share()用法及代碼示例
- Swift Optional.Publisher merge(with:_:_:)用法及代碼示例
- Swift Optional.Publisher map(_:_:)用法及代碼示例
- Swift Optional.Publisher assign(to:on:)用法及代碼示例
- Swift Optional.Publisher output(in:)用法及代碼示例
- Swift Optional.Publisher tryReduce(_:_:)用法及代碼示例
- Swift Optional.Publisher map(_:_:_:)用法及代碼示例
- Swift Optional.Publisher prepend(_:)用法及代碼示例
- Swift Optional.Publisher removeDuplicates()用法及代碼示例
注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 Optional.Publisher zip(_:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。