withViewLifecycleScope

@ExperimentalCoroutinesApi
fun Fragment.withViewLifecycleScope(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 dispatch.android.lifecycle.withViewLifecycleScope
import dispatch.internal.test.Sample4
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.onEach
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
fun main() { 
   //sampleStart 
   class MyViewModel {

  val dataFlow = flow<Data> {
    // ...
  }
}

class MyFragment : Fragment() {

  val myViewModel = MyViewModel()

  val observerJob = withViewLifecycleScope {
    myViewModel.dataFlow.onEach { data ->
      // ...
    }.launchOnCreate()
  }
} 
   //sampleEnd
}

Sources

Link copied to clipboard