CoroutineAutoDispose

Additional

Language
Kotlin
Version
0.1.1 (Dec 25, 2018)
Created
Dec 23, 2018
Updated
Dec 31, 2018
Owner
Sato Shun (satoshun)
Contributor
Sato Shun (satoshun)
1
Activity
Badge
Generate
Download
Source code

Show card

Coroutine AutoDispose

Coroutine AutoDispose is an Kotlin Coroutine library for automatically disposal.

Overview

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(Lifecycle)

LifecycleAutoDisposeInterceptor can use with CoroutineScope. It create a CoroutineInterceptor for automatically disposal with AAC lifecycle events.

abstract class BaseActivity : AppCompatActivity(),
  CoroutineScope {

  override val coroutineContext get() = 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 {
      ...
    }
  }
}

Lifecycle.autoDispose(Job)

This Job an automatically disposal with Android Lifecycle events.

val job = launch { ... }
lifecycle.autoDispose(job)

ViewAutoDisposeInterceptor(Lifecycle)

ViewAutoDisposeInterceptor can use with CoroutineScope. It create a CoroutineInterceptor for automatically disposal with View attach/detach events.

class MainView(context: Context) : View(context), CoroutineScope {
  override val coroutineContext
    get() = Dispatchers.Main +
      ViewAutoDisposeInterceptor(this) // or autoDisposeInterceptor()
  ...
}

Donwload

implementation 'com.github.satoshun.coroutine.autodispose:autodispose:${version}'

etc

This library referred uber/AutoDispose.