observeOn

open fun observeOn(scheduler: Scheduler): Observable<T>

Ensures that downstream observers receive events on the provided scheduler.

This is useful to consume an Observable that emits from a thread different from the consumer's: the source keeps emitting on its own thread, while onNext/onComplete are re-delivered downstream on this scheduler.

Example:

// sourceScheduler: the scheduler the subject emits on
// consumerScheduler: the scheduler the consumer wants its values on
val subject = Observables.publishSubject<Int>()

consumerScheduler.execute {
subject.asObservable()
.subscribeOn(sourceScheduler) // subscribe to `subject` on the scheduler it emits from
.observeOn(consumerScheduler) // hop the emissions over to the consumer
.take(1)
.map { it * 10 }
.subscribe { println(it) }
}

sourceScheduler.execute {
subject.onNext(1)
}

Warning. Disposing of a subscription to the returned Observable must happen from the same scheduler. Disposing from a different scheduler races with event delivery on this scheduler.

Warning. Immediately before observeOn you must subscribeOn the producer scheduler, and you must not chain any operator onto that subscribeOn before calling observeOn. See subscribeOn for the full contract.