实例方法
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()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。