實例方法
erase
eraseToAnyPublisher()
用類型橡皮擦包裝這個發布者。
聲明
func eraseToAnyPublisher() -> AnyPublisher<Self.Output, Self.Failure>
返回值
包裝此發布者的 AnyPublisher
。
詳述
使用 Publisher/eraseToAnyPublisher()
將 AnyPublisher
的實例公開給下遊訂閱者,而不是此發布者的實際類型。這種形式的type erasure
保留了跨 API 邊界的抽象,例如不同的模塊。當您將發布者公開為 AnyPublisher
類型時,您可以隨時間更改底層實現,而不會影響現有客戶端。
以下示例顯示了兩種類型,每種類型都具有 publisher
屬性。 TypeWithSubject
將此屬性公開為其實際類型 PassthroughSubject
,而 TypeWithErasedSubject
使用 Publisher/eraseToAnyPublisher()
將其公開為 AnyPublisher
。從輸出中可以看出,來自另一個模塊的調用者可以訪問 TypeWithSubject.publisher
作為其本機類型。這意味著您不能在不中斷調用者的情況下將發布者更改為其他類型。相比之下,TypeWithErasedSubject.publisher
對調用者顯示為 AnyPublisher
,因此您可以隨意更改底層發布者類型。
public class TypeWithSubject {
public let publisher: some Publisher = PassthroughSubject<Int,Never>()
}
public class TypeWithErasedSubject {
public let publisher: some Publisher = PassthroughSubject<Int,Never>()
.eraseToAnyPublisher()
}
// In another module:
let nonErased = TypeWithSubject()
if let subject = nonErased.publisher as? PassthroughSubject<Int,Never> {
print("Successfully cast nonErased.publisher.")
}
let erased = TypeWithErasedSubject()
if let subject = erased.publisher as? PassthroughSubject<Int,Never> {
print("Successfully cast erased.publisher.")
}
// Prints "Successfully cast nonErased.publisher."
可用版本
iOS 13.0+, iPadOS 13.0+, macOS 10.15+, Mac Catalyst 13.0+, tvOS 13.0+, watchOS 6.0+
相關用法
- Swift Result.Publisher encode(encoder:)用法及代碼示例
- Swift Result.Publisher zip(_:_:_:)用法及代碼示例
- Swift Result.Publisher tryLast(where:)用法及代碼示例
- Swift Result.Publisher sink(receiveCompletion:receiveValue:)用法及代碼示例
- Swift Result.Publisher merge(with:_:_:)用法及代碼示例
- Swift Result.Publisher tryCompactMap(_:)用法及代碼示例
- Swift Result.Publisher print(_:to:)用法及代碼示例
- Swift Result.Publisher sink(receiveValue:)用法及代碼示例
- Swift Result.Publisher setFailureType(to:)用法及代碼示例
- Swift Result.Publisher first(where:)用法及代碼示例
- Swift Result.Publisher output(at:)用法及代碼示例
- Swift Result.Publisher tryCatch(_:)用法及代碼示例
- Swift Result.Publisher dropFirst(_:)用法及代碼示例
- Swift Result.Publisher merge(with:_:_:_:_:_:_:)用法及代碼示例
- Swift Result.Publisher flatMap(maxPublishers:_:)用法及代碼示例
- Swift Result.Publisher map(_:_:_:)用法及代碼示例
- Swift Result.Publisher catch(_:)用法及代碼示例
- Swift Result.Publisher drop(while:)用法及代碼示例
- Swift Result.Publisher prefix(_:)用法及代碼示例
- Swift Result.Publisher timeout(_:scheduler:options:customError:)用法及代碼示例
- Swift Result.Publisher merge(with:_:)用法及代碼示例
- Swift Result.Publisher map(_:)用法及代碼示例
- Swift Result.Publisher append(_:)用法及代碼示例
- Swift Result.Publisher breakpointOnError()用法及代碼示例
- Swift Result.Publisher handleEvents(receiveSubscription:receiveOutput:receiveCompletion:receiveCancel:receiveRequest:)用法及代碼示例
注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 Result.Publisher eraseToAnyPublisher()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。