如何将 currentValueSubject 转换为不可改变的可观察对象?
How can I cast a currentValueSubject to non-mutable observable?
所以我对 RxSwift
比 Combine
熟悉得多。我管理 mutable/immutable 接口的一个好方法是我在 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
因为我知道我只希望从一个地方更新这个流。其他任何地方都应该只从流中读取而没有写入功能。
使用 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)
}
所以我对 RxSwift
比 Combine
熟悉得多。我管理 mutable/immutable 接口的一个好方法是我在 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
因为我知道我只希望从一个地方更新这个流。其他任何地方都应该只从流中读取而没有写入功能。
使用 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)
}