DisposableScope provides an easy way to manage the lifecycle of multiple subscriptions. When the scope is disposed, all subscriptions and disposables associated with it are automatically cleaned up.
You can use the DisposableScope interface via delegation to integrate it directly into your classes (like Presenters or Activities).
Usage Example
val scope = disposableScope {
observable.subscribeScoped(...) // Disposed when scope is disposed
doOnDispose { /* Called when scope is disposed */ }
someDisposable.scope() // someDisposable is disposed when scope is disposed
}
// Later
scope.dispose()
Integration Example
class MyPresenter(...) : DisposableScope by DisposableScope() {
fun load() {
// Subscription will be disposed when the presenter is disposed
longRunningAction.subscribeScoped(onComplete = view::hideProgressBar)
}
}
class MyActivity : AppCompatActivity(), DisposableScope by DisposableScope() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
MyPresenter(...).scope()
}
override fun onDestroy() {
dispose()
super.onDestroy()
}
}
val scope =
disposableScope {
observable.subscribeScoped(...) // Subscription will be disposed when the scope is disposed
doOnDispose {
// Will be called when the scope is disposed
}
someDisposable.scope() // `someDisposable` will be disposed when the scope is disposed
}
// At some point later
scope.dispose()