gpt4 book ai didi

android - 如何在 Jetpack Compose 中正确使用 StateFlow?

转载 作者:行者123 更新时间:2023-12-05 03:35:21 24 4
gpt4 key购买 nike

我在 ViewModel 中执行 API 调用并在可组合项中观察它,如下所示:

class FancyViewModel(): ViewModel(){
private val _someUIState =
MutableStateFlow<FancyWrapper>(FancyWrapper.Nothing)
val someUIState: StateFlow<FancyWrapper> =
_someUIState

fun attemptAPICall() = viewModelScope.launch {
_someUIState.value = FancyWrapper.Loading
when(val res = doAPICall()){
is APIWrapper.Success -> _someUIState.value = FancyWrapper.Loading(res.vaue.data)
is APIWrapper.Error -> _someUIState.value = FancyWrapper.Error("Error!")
}
}
}

在可组合中,我正在像这样听“someUIState”:

@Composable
fun FancyUI(viewModel: FancyViewModel){

val showProgress by remember {
mutableStateOf(false)
}
val openDialog = remember { mutableStateOf(false) }

val someUIState =
viewModel.someUIState.collectAsState()

when(val res = someUIState.value){
is FancyWrapper.Loading-> showProgress = true
is FancyWrapper.Success-> {
showProgress = false
if(res.value.error)
openDialog.value = true
else
navController.navigate(Screen.OtherScreen.route)
}
is FancyWrapper.Error-> showProgress = false
}

if (openDialog.value){
AlertDialog(
..
)
}

Scaffold(
topBar = {
Button(onClick={viewModel.attemptAPICall()}){
if(showProgress)
CircularProgressIndicator()
else
Text("Click")
}
}
){
SomeUI()
}

}

我面临的问题是 FancyUI 可组合项中某些 UIState 的“何时” block 代码在可组合项重组期间被多次触发,即使没有单击脚手架中的按钮(例如:当 AlertDialog 出现时)。我哪里做错了?在 Composable 中使用 StateFlow 观察数据的正确更好方法是什么?

最佳答案

如果你只想处理每个 someUIState 值一次,你应该把它放在 LaunchedEffect 中并传递 someUIState 作为键,这样每当它改变时, block 就会重新触发。

val someUIState by viewModel.someUIState.collectAsState()
LaunchedEffect(someUiState) {
when(someUiState) {
// Same as in the question
}
}

或者,您可以只在 LaunchedEffect 中收集流。

LaunchedEffect(Unit) {
viewModel.someUIState.collect { uiState ->
when(uiState) {
// Same as in the question
}
}
}

关于android - 如何在 Jetpack Compose 中正确使用 StateFlow?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69902138/

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