I have a ProfileViewModel where I load the user profile when the user lands on the screen. To achieve this, I use stateIn so that the profile is fetched automatically.
Now, I want to modify profileUiState to:
Show
isLoading = truebefore callinglogoutApi.logout().Call
logoutApi.logout().Show
isLoading = falseand reload the profile data after logout.
Here’s my current ViewModel:
class ProfileViewModel(
private val userInfoApi: UserInfoApi,
private val logoutApi: LogoutApi,
) : ViewModel() {
private val eventChannel = Channel<ProfileUiEvent>()
val events = eventChannel.receiveAsFlow()
var profileUiState = flow {
val result = userInfoApi.getUserInfo()
emit(
result.fold(
onSuccess = {
ProfileUiState(userInfo = it, isLoading = false)
},
onFailure = {
ProfileUiState(errorMessage = it.message, isLoading = false)
}
)
)
}.stateIn(
scope = viewModelScope,
started = SharingStarted.Lazily,
initialValue = ProfileUiState(isLoading = true)
)
fun onAction(action: ProfileUiEvent) {
viewModelScope.launch {
eventChannel.send(action)
}
}
fun logoutUser() {
viewModelScope.launch {
// update the logic in here for logout
profileUiState
}
}
}
I want to avoid anti-patterns few of them and I read from this blog like :
Calling
getUserInfo()insideinit {}of viewmodel.Using
LaunchedEffectin Compose to trigger an API call.
How can I modify profileUiState properly to handle logout while keeping this approach?