gpt4 book ai didi

android - backStack 到 jetpack compose 界面时再次调用 api

转载 作者:行者123 更新时间:2023-12-05 02:37:29 26 4
gpt4 key购买 nike

我在 View 模型 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
)
)
)
}
})
}
}

最佳答案

您可以使用 LaunchedEffect : 当 View 出现时它会调用一次。

val state = viewModel.state.value
LaunchedEffect(Unit) {
viewModel.clientInfoOnEvent()
}

您可以从 init 中删除此调用,以防止在第一次出现时重复调用。在 documentation 中查看有关 Compose 副作用的更多信息.

关于android - backStack 到 jetpack compose 界面时再次调用 api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69962501/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com