Alexa_Gal
01/29/2021, 6:33 PMauthMethod
)
viewModel.authMethod.onEach {
Log.e("i'm here", "yes im here ${it}")
}.collect()
this will be trigger the first time and every time after i change the value on the viewModel.
my issue is that when i push new view (using Navigation alpha06
) and i pop back the onEach
will be triggered again. How could i only tell authMethod
to be triggered only on changes and not every-time the compose is rendering ?🌈
With liveData i had the observable that only triggers on changes, but i can not find the equivalent on StateFlow :/Zach Klippenstein (he/him) [MOD]
01/29/2021, 6:35 PMcollect()
from? LaunchedEffect
?Alexa_Gal
01/29/2021, 6:36 PMval coroutineScope = rememberCoroutineScope()
LaunchedEffect(coroutineScope) {
viewModel.authMethod.onEach {
Log.e("ime here", "yes im here ${it}")
}.launchIn(coroutineScope)
}
Joost Klitsie
01/29/2021, 7:20 PMZach Klippenstein (he/him) [MOD]
01/29/2021, 7:23 PMrememberCoroutineScope
and LaunchedEffect
- that’s redundant, use one or the other. The parameter to LaunchedEffect
should be a thing that will cause the coroutine to restart if it changes (i.e. the data dependency of the coroutine). This could just be
LaunchedEffect(viewModel.authMethod) {
viewModel.authMethod.collect {
Log.e("ime here", "yes im here $it")
}
}
Zach Klippenstein (he/him) [MOD]
01/29/2021, 7:27 PMJoost Klitsie
01/29/2021, 7:49 PMJoost Klitsie
01/29/2021, 7:49 PMJoost Klitsie
01/29/2021, 7:49 PMAlexa_Gal
01/29/2021, 7:59 PMAlexa_Gal
01/29/2021, 8:01 PMShakil Karim
01/29/2021, 9:48 PMAdam Powell
01/30/2021, 3:58 PMAdam Powell
01/30/2021, 3:59 PM@Composable
function:
// fire a one-off event to get the recipe from api
val onLoad = viewModel.onLoad.value
if (!onLoad){
viewModel.onLoad.value = true
viewModel.onTriggerEvent(RecipeEvent.GetRecipeEvent(recipeId))
}
Here are several reasons why:Adam Powell
01/30/2021, 4:01 PMAdam Powell
01/30/2021, 4:03 PM*Effect
APIs: SideEffect
, DisposableEffect
, LaunchedEffect
. The viewModel.onTriggerEvent
call is an unsafe side effect as written.Adam Powell
01/30/2021, 4:03 PMAdam Powell
01/30/2021, 4:04 PMAdam Powell
01/30/2021, 4:12 PM// In composition
SideEffect {
viewModel.onComposed(recipeId)
}
This places responsibility for any deduplication or policy enforcement on the viewmodel class instead, where it is much easier to confirm and test. It makes the composable function much simpler too!Adam Powell
01/30/2021, 4:15 PM