Forked from mahdiPourkazemi/gist:5b30e934e1bb48d0636a4f9d5aa6b222
Created
June 2, 2022 01:24
-
-
Save munho/b9aa85f8b984789e1017af86b6f3b7ab to your computer and use it in GitHub Desktop.
remove bracket hell for using flow
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
가이드: 아키텍처 구성요소 > 아키텍처 구성요소로 Kotlin 코루틴 사용 > 재시작 가능한 수명 주기 인식 코틀린
https://developer.android.com/topic/libraries/architecture/coroutines?hl=ko#restart