我當前的Android Jetpack Compose應用程序使用snapShotFlow
將mutableStateOf()
轉換為流并觸發用戶操作,如下所示
In ViewModel:-
var displayItemState by mutableStateOf(DisplayItemState())
@Immutable
data class DisplayItemState(
val viewIntent: Intent? = null
)
In composable:-
val displayItemState = viewModel.displayItemState
LaunchedEffect(key1 = displayItemState) {
snapshotFlow { displayItemState }
.distinctUntilChanged()
.filter { it.viewIntent != null }
.collectLatest { displayItemState ->
context.startActivity(displayItemState.viewIntent)
}
}
當我將測試設備保持在縱向或橫向時,一切都按預期工作。
但是,當我更改設備方向時,將重新發送上次收集的snapShotFlow
值。
如果我在snapShotFlow中按如下方式重置displayItemState,這將修復問題,但這感覺是錯誤的修復。我做錯了什么?阻止snapShotFlow在方向更改時重新觸發的正確方法是什么
val displayItemState = viewModel.displayItemState
LaunchedEffect(key1 = displayItemState) {
snapshotFlow { displayItemState }
.distinctUntilChanged()
.filter { it.viewIntent != null }
.collectLatest { displayItemState ->
context.startActivity(displayItemState.viewIntent)
viewModel.displayItemState = DisplayItemState()
}
}
這是有意的行為,你沒有做錯任何事。Compose的
(Mutable)State
保存最后一個值,類似于StateFlow
,因此它們的新集合總是以最后一個數值開始。您的解決方案是好的,Android的應用程序架構指南中實際上推薦了非常類似的內容:
另一種可能是在viewModel中使用
SharedFlow
而不是MutableState
-SharedFlow
不保留最后一個值,因此不會出現此問題。