Steffen Funke
11/25/2021, 6:40 AMState<T>
AND a StateFlow<T>
, backed by the same changing data, at the same time from an Android ViewModel? I have some View based UI which consumes the data as StateFlow
, and some Compose UI, which would need State
. And ideally I don’t want to rewrite the Compose part to collectAsState()
, rather just have it consume State directly from ViewModel (e.g. hide the implementation details inside ViewModel):
Inside ViewModel:
// is consumed by View based UI
protected val _itemsFlow = MutableStateFlow<List<Item>>(emptyList())
val itemsFlow = _itemsFlow.asStateFlow()
// should be consumed by Compose UI
val items: State<List<Item>> = itemsFlow.collectAsState() // not working bc. of missing @Composable scope
val items: State<List<Item>> = itemsFlow.collectAsState(emptyList()) // also not working
Zoltan Demant
11/25/2021, 6:43 AMState<T>
over StateFlow<T>
in your ViewModel, if thats a viable option for you?Steffen Funke
11/25/2021, 6:44 AMmutableStateOf(List<T>)
inside VM, and get an StateFlow<List<T>>
out of it 🤔 ?Zoltan Demant
11/25/2021, 6:46 AMSteffen Funke
11/25/2021, 6:48 AMSteffen Funke
11/25/2021, 6:49 AMSnapshotFlow
be a way to convert mutablestate to StateFlow? Have to read about it.Steffen Funke
11/25/2021, 6:52 AMitemsFlow
updating, when items
are?
// Inside VM
var items by mutableStateOf(emptyList<Item>())
protected set
val itemsFlow = snapshotFlow { items }
Zoltan Demant
11/25/2021, 6:53 AMclass StateExample<State>(initial: State) {
private val state = MutableStateFlow(initial)
val composableState
@Composable
get() = state.collectAsState()
}
@Composable
fun Test(example: StateExample<String>) {
val state by example.composableState
state // <- String!
}
Steffen Funke
11/25/2021, 11:23 AMsnapshotFlow
was the missing piece to convert a mutableStateOf
into StateFlow<T>
, see above. Working now! 🥳Jaime
11/26/2021, 1:54 AM