Coroutine AutoDispose is an Kotlin Coroutine library for automatically disposal.
Often, Coroutine subscriptions need to stop in response to some event (like a Activity#onStop()). In order to support this common scenario in Coroutine.
LifecycleAutoDisposeInterceptor can use with CoroutineScope. It create a CoroutineInterceptor for automatically disposal with AAC lifecycle events.
abstract class BaseActivity : AppCompatActivity(),
CoroutineScope {
private val job = Job()
override val coroutineContext get() = job +
Dispatchers.Main +
LifecycleAutoDisposeInterceptor(this) // or autoDisposeInterceptor()
}
class MainActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
// automatically dispose when onDestroy
launch {
...
}
}
override fun onResume() {
// automatically dispose when onPause
launch {
...
}
}
}
This Job an automatically disposal with Android Lifecycle events.
val job = launch { ... }
lifecycle.autoDispose(job)
ViewAutoDisposeInterceptor can use with CoroutineScope. It create a CoroutineInterceptor for automatically disposal with View attach/detach events.
class MainView(context: Context) : View(context), CoroutineScope {
private val job = Job()
override val coroutineContext
get() = job +
Dispatchers.Main +
ViewAutoDisposeInterceptor(this) // or autoDisposeInterceptor()
...
}
implementation 'com.github.satoshun.coroutine.autodispose:autodispose:${version}'
This library referred uber/AutoDispose.