Vitaliy Zarubin
06/01/2021, 9:23 AMval user by viewModel.loadingUser.collectAsState(initial = null)
when {
user.isSucceeded -> navController.navigate(NavScreen.Home.route)
user.isError -> ErrorConnect { viewModel.repeat() }
else -> Splash()
}
knthmn
06/01/2021, 9:31 AMwhen
block in a composable? Also what is ErrorConnect
? Can you show more of your code.Vitaliy Zarubin
06/01/2021, 9:33 AMVitaliy Zarubin
06/01/2021, 9:34 AMVitaliy Zarubin
06/01/2021, 9:41 AMPaul Woitaschek
06/01/2021, 9:50 AMknthmn
06/01/2021, 9:51 AMrepeat()
does not restart the .collectAsState()
, instead it just starts collecting the flow independently. Is there a way you can get a flow of the latest user
value from your ServiceUser
?
2. Code with side effects (such as NavController.navigate()
) should not be in composable function (see [1]). In your case you can simply switch between what is being displayed by the value of user
val user by viewModel.loadingUser.collectAsState(null)
when {
user.isSuceeded -> TabsHome(...)
user.isError -> Error()
null -> Splash()
}
Although I don't see the case here, if you really need to have the different screens as destinations , use LaunchedEffect()
val user by viewModel.loadingUser.collectAsState(null)
LaunchedEffect(user) {
... navigate depending on the value of user ...
}
[1] https://developer.android.com/jetpack/compose/side-effectsVitaliy Zarubin
06/01/2021, 11:38 AMPaul Woitaschek
06/01/2021, 11:40 AMVitaliy Zarubin
06/01/2021, 11:51 AMknthmn
06/01/2021, 1:05 PMRepositoryUser.loadingUser()
finishes, I would probably do this
private val _loadingUser: MutableStateFlow<ResponseResult<ModelUser>> = MutableStateFlow(null)
val loadingUser = _loadingUser.asStateFlow()
init {
reload()
}
fun reload() {
repository.loadingUser()
.onEach { loadingUser.value = it }
.launchIn(viewModelScope)
}
knthmn
06/01/2021, 1:10 PMServiceUser.getUser()
cannot be made reactive, I wouldn't bother to wrap it in a flow as you did in loadingUser()
. If I see a Flow
, I assume it to always provides me with the latest valueVitaliy Zarubin
06/01/2021, 1:15 PMknthmn
06/01/2021, 1:16 PMVitaliy Zarubin
06/02/2021, 4:49 PMWhy would you annotate a launching function as worker thread?https://developer.android.com/studio/write/annotations#thread-annotations
Paul Woitaschek
06/02/2021, 4:51 PMPaul Woitaschek
06/02/2021, 4:53 PMPaul Woitaschek
06/02/2021, 4:56 PM