因此,我对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 { }
}
如何使用Combine
做类似的事情? Combine的currentValueSubject
似乎没有办法将其转换为非读写版本。还是我错过了什么?
在我的应用中,我不想直接传递currentValueSubject
,因为我知道我只希望从一个地方更新此流。其他任何地方都应该仅从流中读取并且不具有写功能。
答案 0 :(得分:0)
使用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)
}