parbo
parbo

Reputation: 253

How to not invalidate observer when binding is disposed in RxSwift?

I'm quite new in RxSwift world and apparently I'm not using it correctly... I have a button that I would like to connect to an observer like this

button.rx.tap.bind(to: viewModel.someObserver).disposed(by: disposeBag)

where someObserver in viewModel is initialized as follows:

let publishSubject = PublishSubject<Void>()
someObserver = publishSubject.asObserver()
someObservable = publishSubject.asObservable() 

However, when Disposable created with binding is disposed, PublishSubject which is used both as Observer and Observable gets invalidated and all new subscriptions are immediately disposed.

I would like to use my PublishSubject for a longer time and be able to subscribe to it after the binding is disposed. How to achieve that?

Upvotes: 0

Views: 1082

Answers (1)

fphilipe
fphilipe

Reputation: 10056

Have a look at PublishRelay, which can't terminate with an error or completed event.

Binding the taps to a PublishRelay will simply ignore the completed event (source) once the subscription is disposed, e.g. when the button is deallocated. This will allow you to subscribe to the PublishRelay at a later point

Upvotes: 4

Related Questions