【发布时间】:2021-12-25 22:59:23
【问题描述】:
我在视图模型init 中调用了一个API。当我导航到另一个屏幕并返回上一个屏幕时,我想再次调用 API clientInfoOnEvent() 来更新数据,但我可以在 Jetpack Compose 中完成。我该怎么做?
Viewwmodel 代码:
@HiltViewModel
class ProfileViewModel @Inject constructor(
private val profileUseCases: ProfileUseCases,
private val clientNavigator: ClientNavigator,
private val isLoggedInDataStore: IsLoggedInDataStore
) :
ViewModel(), ClientNavigator by clientNavigator {
private val _state = mutableStateOf(ProfileState())
val state: State<ProfileState> = _state
init {
clientInfoOnEvent()
}
fun clientInfoOnEvent() {
profileUseCases.getClientInfoUseCase().onEach { result ->
when (result) {
is Resource.Success -> {
_state.value = state.value.copy(info = result.data)
}
is Resource.Error -> {
_state.value =
state.value.copy(error = result.message ?: "An unexpected error occurred")
}
is Resource.Loading -> {
_state.value = state.value.copy(isLoading = true)
}
}
}.launchIn(viewModelScope)
}
}
屏幕代码:
val state = viewModel.state.value
Column(
modifier = modifier.fillMaxWidth(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.Start
) {
state.info?.apply {
Text(
text = "$givenName $lastName",
style = AppFont.PoppinsTypography.button,
color = AppColor.neutralColor.CHARCOAL,
modifier = modifier.padding(top = 4.dp, bottom = 4.dp)
)
val clientData = let {
it.copy(currency = Currency().copy(signSvg = it.currency?.signSvg.urlEncoder()))
}
TextIcon(
text = stringResource(R.string.edit_profile),
icon = painterResource(id = R.drawable.ic_right),
color = AppColor.neutralColor.SPANISH_GRAY,
style = AppFont.PoppinsTypography.caption,
onCLick = {
state.info?.let {
viewModel.navigate(
EditProfileDestination.createEditProfileRoute(
Gson().toJson(
clientData
)
)
)
}
})
}
}
【问题讨论】:
标签: android kotlin android-jetpack-compose