Skip to content

1.0.2

Choose a tag to compare

@skydoves skydoves released this 19 Apr 12:03

🎉 Released a new version 1.0.2! 🎉

Coroutines and Flow

Add a dependency code to your module's build.gradle file.

dependencies {
    implementation "androidx.lifecycle:lifecycle-runtime-ktx:$versions.lifecycle" // over the 2.4.0-alpha01
}

We can apply to the coroutines lifecycleScope for launching suspend functions. The Lifecycle-runtime-ktx supports launchWhenStarted, launchWhenCreated, and launchWhenResumed for the lifecycleScope. However those coroutines jobs will not be canceled automatically, so they must be canceled on a specific lifecycle. And we can declare canceling together with initialization like the below.

private val job: Job by lifecycleAware {
    lifecycleScope.launchWhenCreated {
      // call suspend
    }
  }.onDestroy {
    cancel() // cancel when the lifecycle is destroyed.
  }.lazy()

We can reduce the above codes like the below using the launchOnStarted, launchOnCreated, and launchOnResume.

private val job: Job by launchOnStarted {
    // call suspend
  }.onDestroy {
    cancel()
  }.lazy()

If we need to collect one flow on the coroutines lifecycle scope, we can use like the below.

private val job: Job by launchOnStarted(repository.fetchesDataFlow()) {
    // collected value from the repository.fetchesDataFlow()
  }.onDestroy {
    cancel()
  }.lazy()

addOnRepeatingJob

The addRepeatingJob extension has been added in the new version of the Lifecycle-runtime-ktx.

Launches and runs the given block in a coroutine when this LifecycleOwner's Lifecycle is at least at state. The launched coroutine will be canceled when the lifecycle state falls below the state.

We can collect a flow on the coroutines lifecycle scope and cancel it automatically if the lifecycle falls below that state, and will restart if it's in that state again.

private val job: Job by addOnRepeatingJob(Lifecycle.State.CREATED, simpleFlow()) {
    // collected value from the fetchesDataFlow()
  }.lazy()