Prepare
app/build.gradle
ext {
rxjava2_version = "2.1.7"
}
dependencies {
implementation "io.reactivex.rxjava2:rxjava:${rxjava2_version}"
}
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
}
}
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()
}
}
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) }
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)
Top comments (1)
hi, im just curious abit about, why should you put composite disposable onStart() ?