简体   繁体   English

如何将 currentValueSubject 转换为非可变的 observable?

[英]How can I cast a currentValueSubject to non-mutable observable?

So I'm much more familiar with RxSwift than Combine .所以我对RxSwift比对Combine更熟悉。 A good way I manage mutable/immutable interfaces is I do something like this in RxSwift我管理可变/不可变接口的一个好方法是我在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 { }
}

How can I do something similar using Combine ?如何使用Combine做类似的事情? Combine's currentValueSubject doesn't appear to have a way to cast this down to a non-read write version. Combine 的currentValueSubject似乎没有办法将其转换为非读写版本。 Or am I missing something?或者我错过了什么?

In my app, I don't want to directly pass down a currentValueSubject since I know for a fact I only want this stream updated from one place.在我的应用程序中,我不想直接传递currentValueSubject因为我知道一个事实,我只想从一个地方更新这个流。 Everywhere else should just read from the stream and not have write capability.其他任何地方都应该只从流中读取,而没有写入能力。

Use AnyPublisher as your non-mutable type:使用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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM