How to use CompositeDisposable of RxJava 2?

前端 未结 3 528
心在旅途
心在旅途 2021-01-30 03:17

In RxJava 1, there was CompositeSubscription, but that is not present in RxJava2, There is something CompositeDisposable in rxJava2. How do I use CompositeDisposable or Disposab

3条回答
  •  孤独总比滥情好
    2021-01-30 03:20

    CompositeDisposable cannot be reused after being disposed. If you want sync disposable lifecycle with Android Activity lifecycle, it is possible to correspond by making a simple wrapper.

    class AndroidDisposable {
        private var compositeDisposable: CompositeDisposable? = null
    
        fun add(disposable: Disposable) {
            if (compositeDisposable == null) {
                compositeDisposable = CompositeDisposable()
            }
            compositeDisposable?.add(disposable)
        }
    
        fun dispose() {
            compositeDisposable?.dispose()
            compositeDisposable = null
        }
    }
    

    How to use:

    class MainActivity : AppCompatActivity() {
        private disposable = AndroidDisposable()
    
        override fun onStart() {
            super.onStart()
            disposable.add(/* Some disposable */)
        }
    
        override fun onStop() {
            disposable.dispose()
            super.onStop()
        }
    }
    

提交回复
热议问题