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

Viewed 488

So I'm much more familiar with RxSwift than Combine. A good way I manage mutable/immutable interfaces is I do something like this in 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's currentValueSubject doesn't appear to have a way to cast this down to a non-read write version. 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. Everywhere else should just read from the stream and not have write capability.

1 Answers

Use AnyPublisher as your non-mutable type:

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)
}
Related