Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save munho/b9aa85f8b984789e1017af86b6f3b7ab to your computer and use it in GitHub Desktop.
Save munho/b9aa85f8b984789e1017af86b6f3b7ab to your computer and use it in GitHub Desktop.
remove bracket hell for using flow
fun <T> StateFlow<T>.collectIt(lifecycleOwner: LifecycleOwner, function: (T) -> Unit) {
// Create a new coroutine in the lifecycleScope
lifecycleOwner.lifecycleScope.launch {
// repeatOnLifecycle launches the block in a new coroutine every time the
// lifecycle is in the STARTED state (or above) and cancels it when it's STOPPED.
lifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED){
collect {
// Trigger the flow and start listening for values.
// This happens when lifecycle is STARTED and stops
// collecting when the lifecycle is STOPPED
function.invoke(it)
}
}
}
}
@munho
Copy link
Author

munho commented Jun 2, 2022

가이드: 아키텍처 구성요소 > 아키텍처 구성요소로 Kotlin 코루틴 사용 > 재시작 가능한 수명 주기 인식 코틀린
https://developer.android.com/topic/libraries/architecture/coroutines?hl=ko#restart

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment