A. Steenbergen
A. Steenbergen

Reputation: 3440

Best way of creating an Observable in RxJava 2 to be able to use the emitter for mvvm

My intention is to create an Observable that can be made to emit an item inside a class.

My goal is to create a ViewModel, which can expose a stream to a View in Android, reactively delivering items.

My approach is as follows:

class MyMVVM {
  private lateinit var timeSelectedEmitter: ObservableEmitter<Int> 
  val timeSelectedObservable: Observable<Int> = Observable.create { emitter -> timeSelectedEmitter = emitter }
}

This should, in theory and as far as I understand it currently, give me access to the emitter, which then can be called at any point to deliver time-events to subscribers of timeSelectedObservable (subscribers which are inside the View)

1) Is this a correct approach or should this be done in another way?

2) Is there a way for the emitter to be created on Observable creation instead of when a subscriber is subscribing to the Observable (to avoid nullpointer exceptions or Kotlin exceptions)?

Thanks.

Upvotes: 1

Views: 748

Answers (1)

triad
triad

Reputation: 21567

I usually create the Observable once and return the same Observable to anything that wants to subscribe to it. This way, if there are multiple subscribers, a new Observable doesn't need to be created each time.

So something like:

class ViewModel {
    private val timeObservable = PublishSubject.create<Int>()
    fun timeObservable(): Observable<Int> = timeObservable

    fun update() {
        // ...
        timeObservable.onNext(time)
    }
}

class Activity {
    ...
    viewModel.timeObservable()
        .subscribe { 
            time -> ...
        })
}

Upvotes: 1

Related Questions