如何将currentValueSubject转换为不可观察的变量?

时间:2020-03-17 01:28:27

标签: ios swift combine

因此,我对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,因为我知道我只希望从一个地方更新此流。其他任何地方都应该仅从流中读取并且不具有写功能。

1 个答案:

答案 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)
}
相关问题