/CoroutineAutoDispose

Coroutine AutoDispose is an Kotlin Coroutine library for automatically disposal.

Primary LanguageKotlinApache License 2.0Apache-2.0

Coroutine AutoDispose

CircleCI Maven Central Android Arsenal

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 {

  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 {
      ...
    }
  }
}

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 {
  private val job = Job()
  override val coroutineContext
    get() = job +
      Dispatchers.Main +
      ViewAutoDisposeInterceptor(this) // or autoDisposeInterceptor()
  ...
}

Donwload

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

etc

This library referred uber/AutoDispose.