-
-
Save marcellogalhardo/a9985f7b3875fa41c379a2ba65d8ac9c to your computer and use it in GitHub Desktop.
This file contains 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
// For more details, check: https://gist.github.com/marcellogalhardo/88cd1b17a41e82acc9913448ee316094 | |
fun <T> Flow<T>.observeIn(lifecycleOwner: LifecycleOwner, observer: (T) -> Unit) { | |
asLiveData().observe(lifecycleOwner, observer) | |
} | |
// For more details, check: https://gist.github.com/marcellogalhardo/88cd1b17a41e82acc9913448ee316094 | |
inline fun <T> Flow<T>.collectWhenStartedIn( | |
lifecycleOwner: LifecycleOwner, | |
crossinline action: suspend (value: T) -> Unit | |
): Job { | |
return lifecycleOwner.lifecycleScope.launchWhenStarted { collect(action) } | |
} | |
// For more details, check: https://gist.github.com/marcellogalhardo/88cd1b17a41e82acc9913448ee316094 | |
inline fun <T> Flow<T>.collectIn( | |
scope: CoroutineScope, | |
crossinline action: suspend (value: T) -> Unit | |
): Job { | |
return scope.launch { collect(action) } | |
} | |
// For more details, check: https://gist.github.com/marcellogalhardo/2a1ec56b7d00ba9af1ec9fd3583d53dc | |
fun <T> SavedStateHandle.getStateFlow( | |
scope: CoroutineScope, | |
key: String, | |
initialValue: T | |
): MutableStateFlow<T> { | |
val liveData = getLiveData(key, initialValue) | |
val stateFlow = MutableStateFlow(initialValue) | |
val observer = Observer<T> { value -> | |
if (value != stateFlow.value) { | |
stateFlow.value = value | |
} | |
} | |
liveData.observeForever(observer) | |
stateFlow.onCompletion { | |
withContext(Dispatchers.Main.immediate) { | |
liveData.removeObserver(observer) | |
} | |
}.onEach { value -> | |
withContext(Dispatchers.Main.immediate) { | |
if (liveData.value != value) { | |
liveData.value = value | |
} | |
} | |
}.launchIn(scope) | |
return stateFlow | |
} | |
// For more details, check: https://gist.github.com/marcellogalhardo/9c111ff481e6718da3c1553f795174b9 | |
fun <T : View> launchViewInFragment( | |
@StyleRes themeResId: Int = R.style.FragmentScenarioEmptyFragmentActivityTheme, | |
instantiate: ViewFactory<T> | |
): FragmentScenario<ViewHostFragment<T>> = launchFragmentInContainer( | |
themeResId = themeResId, | |
instantiate = { ViewHostFragment(instantiate) } | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment