DEV Community

Ryutaro Miyashita
Ryutaro Miyashita

Posted on

How to make reusable CompositeDisposable and Kotlin extension

Prepare

app/build.gradle

ext {
  rxjava2_version = "2.1.7"
}
dependencies {
  implementation "io.reactivex.rxjava2:rxjava:${rxjava2_version}"
}
Enter fullscreen mode Exit fullscreen mode

Make "AndroidDisposable"

Edit

The same effect can be obtained by using "CompositeDisposable#clear"

CompositeDisposable is can not reuse when already disposed. If you want sync disposable lifecycle with Android Activity lifecycle, it is possible to correspond by making 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
    }
}
Enter fullscreen mode Exit fullscreen mode

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()
    }
}
Enter fullscreen mode Exit fullscreen mode

Kotlin Extension

Kotlin can add new function / method for existing class (An entity is a static method that takes an instance of the target class as the first argument). I will extend Disposable and make it easy to use AndroidDisposable.

operator fun AndroidDisposable.plusAssign(disposable: Disposable) {
    add(disposable)
}

fun Disposable.addTo(androidDisposable: AndroidDisposable): Disposable
    = apply { androidDisposable.add(this) }
Enter fullscreen mode Exit fullscreen mode

How to use

val texts = listOf("1", "2", "3")

// Operator
disposable += Observable.fromIterable(texts)
    .map { it.toInt(10) }
    .reduce { t1, t2 -> t1 + t2 }
    .subscribe()

// or
Observable.fromIterable(texts)
    .map { it.toInt(10) }
    .reduce { t1, t2 -> t1 + t2 }
    .subscribe()
    .addTo(disposable)
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
gideonseven profile image
Gideon Steven Tobing

hi, im just curious abit about, why should you put composite disposable onStart() ?