[Compose] Defining a "collectAsEffect" extension for Compose to reduce boilerplate code
luongvo opened this issue · comments
Luong Vo (Lucas) commented
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:
- https://github.com/elson-dsouza/PopMovies/blob/dce98cd63540e6c88b8913a978c78edaf2fe035e/app/src/main/java/com/example/elson/popmovies/compose/EventsSupport.kt
- https://github.com/igamgam97/MovieDB/blob/a2cd3e0dd171115c9d422f96944e0b19a41cee95/core/common/src/main/java/com/noveogroup/moviecatalog/core/common/FlowExt.kt
- https://github.com/Cilestal/Kotlin-Multiplatform-MVI-sample-Android-Compose-iOS-SwiftUI-/blob/7e68ec688ef7c0685a883a708c06454fe60d8d0c/androidApp/src/main/java/com/cilestal/mvi_mpp/android/extension/ComposeExt.kt
- https://github.com/adiRandom/grocever-android/blob/eab84e8a6294a7ad429a51f5353620d35e6b033b/app/src/main/java/app/adi_random/dealscraper/usecase/FlowUtils.kt
- https://github.com/adiRandom/grocever-android/blob/39fc41cd46ef0f6497b289059359c3bb56e1b0c3/app/src/main/java/app/adi_random/dealscraper/usecase/FlowUtils.kt
Who Benefits?
Developers