CoroutineAutoDispose

Introduction: Coroutine AutoDispose is an Kotlin Coroutine library for automatically disposal.
More: Author   ReportBugs   
Tags:

CircleCI Maven Central codecov

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()
  ...
}

It can also be used from extension functions

val view = ...
view.autoDisposeScope.launch {
  ...
}

Use with RecyclerView

CoroutineScope can be used from a itemView of RecyclerView.ViewHolder.

override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
  holder.itemView.autoDisposeScope.launch {
    ...
  }
}

Download

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

etc

This library referred uber/AutoDispose.

Support Me
Apps
About Me
Google+: Trinea trinea
GitHub: Trinea