所以我RxSwift比更熟悉Combine。管理可变/不可变接口的一个好方法是我在RxSwift
protocol SampleStream {
/// An immutable interface.
var streamInfo: Observable<String?> { get}
}
protocol MutableSampleStream: SampleStream {
/// A mutable interface.
func updateStream( _ val: String?)
}
func SampleStreamImpl: MutableSampleStream {
// Returns the immutable version of the stream.
// If I pass down SampleStream as a dependency, then nothing else can write to this stream.
// When they subscribe, they immediately get a value though since it's a behavior subject.
var streamInfo: Observable<String?> {
return streamInfoSubject.asObservable()
}
private var streamInfoSubject = BehaviorSubject<String?>(value: nil)
func updateStream { }
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能使用 做类似的事情Combine?组合currentValueSubject似乎没有办法将其转换为非读写版本。或者我错过了什么?
在我的应用程序中,我不想直接传递 acurrentValueSubject因为我知道我只希望从一个地方更新此流。其他地方应该只从流中读取,而不具有写入功能。
用作AnyPublisher您的非可变类型:
protocol SampleStream {
var streamInfo: AnyPublisher<String?, Error> { get }
}
protocol MutableSampleStream: SampleStream {
func updateStream(_ val: String?)
}
class MySampleStream: MutableSampleStream {
var streamInfo: AnyPublisher<String?, Error> {
return subject.eraseToAnyPublisher()
}
func updateStream(_ val: String?) { subject.send(val) }
private let subject = CurrentValueSubject<String?, Error>(nil)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
869 次 |
| 最近记录: |