Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// 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