CoroutineAutoDispose

Additional

Language
Kotlin
Version
0.2.0 (Apr 29, 2019)
Created
Dec 23, 2018
Updated
Jul 27, 2019
Owner
Sato Shun (satoshun)
Contributor
Sato Shun (satoshun)
1
Activity
Badge
Generate
Download
Source code
APK file

Advertising

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

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.