Convert RxJava Observables To Live Data With Kotlin Extension Functions

前端 未结 3 465
攒了一身酷
攒了一身酷 2021-01-30 14:26

I\'ve been using alot of RxJava Observables converted to LiveData in my code using LiveDataReactiveStreams.fromPublisher() library. So I t

3条回答
  •  被撕碎了的回忆
    2021-01-30 15:06

    Your solution is fine if you want to use LiveData and Rx together.

    If you just want to auto-dispose your subscription you could implement it on Disposable like this:

    private class LifecycleDisposable(obj: Disposable) :
            DefaultLifecycleObserver, Disposable by obj {
        override fun onStop(owner: LifecycleOwner) {
            if (!isDisposed) {
                dispose()
            }
        }
    }
    
    fun Disposable.attachToLifecycle(owner: LifecycleOwner) {
        owner.lifecycle.addObserver(LifecycleDisposable(this))
    }
    

    and call it like

    Observable.just(1, 2, 3).subscribe().attachToLifecycle(this)
    

    where this references any LifecycleOwner.

提交回复
热议问题