withViewLifecycle

@ExperimentalCoroutinesApi
fun CoroutineScope.withViewLifecycle(fragment: Fragment, block: ViewLifecycleCoroutineScope.() -> Unit): Job

CoroutineScope helper for a Fragment's ViewLifecycleOwner.

This function observes a Fragment's viewLifecycleOwnerLiveData, and invokes block.

Samples

import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModel
import dispatch.android.lifecycle.withViewLifecycle
import dispatch.core.MainImmediateCoroutineScope
import dispatch.internal.test.android.LiveDataTest
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.onEach
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
fun main() { 
   //sampleStart 
   class MyFragment @Inject constructor(
  scope: MainImmediateCoroutineScope
) : Fragment() {

  val myViewModel by viewModels<MyViewModel>()

  val observerJob = scope.withViewLifecycle(this) {
    // this lambda is invoked every time the View lifecycle is set
    myViewModel.dataFlow.onEach { data ->
      // ...
    }.launchOnCreate()
  }
} 
   //sampleEnd
}

Sources

Link copied to clipboard