paco8
paco8

Reputation: 83

RxSwift: Pass actual observable to another view controller?

I have a view controller that needs to know about a boolean variable headerCollapsed that is set from another view controller. In vc1 I have:

headerCollapsed = ReplaySubject<Bool>.create(bufferSize: 1)
collapsedObservable = headerCollapsed.asObservable()

and a function that sets the boolean to true:

func updateHeader() {
    self.headerCollapsed.onNext(true)
}

Then, to avoid creating further dependencies and calling vc1 directly, I am trying to pass collapsedObservable, not headerCollapsed, all the way to vc2 through dependency injection and a router. I am trying to simplify the issue, but there are actually several layers between vc1 and vc2.

What is happening though is that inside my router class collapsedObservable is nil no matter what, and I am not able to set it to a default value to be updated later when I call it from inside vc2. So, is passing the actual observable like this even possible?

Upvotes: 1

Views: 801

Answers (2)

Daniel T.
Daniel T.

Reputation: 33967

If you don't make collapsedObservable optional, then it can never be nil.

class ViewController: UIViewController {

    private let headerCollapsed = ReplaySubject<Bool>.create(bufferSize: 1)
    lazy var collapsedObservable = headerCollapsed.asObservable()
}

Upvotes: 0

Adis
Adis

Reputation: 4552

Why do you need to convert the ReplaySubject to Observable anyway?

It looks to me like you could just use a Relay (BehaviorRelay if you want the initial state) instead (doesn't complete, doesn't error which is exactly what you need) and just pass the Relay directly to vc2.

Upvotes: 1

Related Questions