nimblehq / android-templates

Our optimized Android templates used in our projects

Home Page:https://nimblehq.co/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[Compose] Defining a "collectAsEffect" extension for Compose to reduce boilerplate code

luongvo opened this issue · comments

Why

On the way of defining some valuable extensions for Compose to reduce boilerplate code, we can define a collectAsEffect:

@Composable
fun <T> Flow<T>.collectAsEffect(
    context: CoroutineContext = EmptyCoroutineContext,
    block: (T) -> Unit
) {
    LaunchedEffect(key1 = Unit) {
        onEach(block).flowOn(context).launchIn(this)
    }
}

So with a long implementation like this 🤔 ,

LaunchedEffect(viewModel.error) {
    viewModel.error.collect { error -> error.showToast(context) }
}

LaunchedEffect(viewModel.navigator) {
    viewModel.navigator.collect { destination -> navigator(destination) }
}

we can now shorten it by using the above collectAsEffect extension 👏

viewModel.error.collectAsEffect { error -> error.showToast(context) }
viewModel.navigator.collectAsEffect { destination -> navigator(destination) }

RFC discussion: #408

References:

Who Benefits?

Developers