Hii, I wanted to know if it is better to keep Stat...
# compose
a
Hii, I wanted to know if it is better to keep State<UiModels> in view models or keeping StateFlow<UiModels> in view models and then in compose layout collect their value to a state? What would be preferable here?
f
Both have advantages and disadvantages. We ended up using State<UiState> in our app but you might have different needs.
a
@Filip Wiesner if you could please brief me about pros and cons then that would be really helpful. Or point me to some article maybe. To me, keeping ui state in stateflow seems a bit excessive since we are already keeping the domain models in state and then mapping those states to ui models.
f
Flow has advantage in it's operators. You can
map
,
filter
,
merge
and so on. Also Flow in it's general concept exists on other platforms like iOS so if you would want to share your VM with multiple platforms than that would help. But both of these problems can be solved using
snapshotFlow {}
if needed.
a
@Filip Wiesner cool, will look into that. thanks
s
Your ViewModel doesn’t need to be aware that it’s used by Compose. You won’t be missing out on anything if it’s a StateFlow instead, if anything it’s even nicer.
f
You'll be missing out on the ease of use. And the "it’s even nicer" part is purely subjective 😄 But yeah, I guess this whole discussion is subjective so it might as well be nicer.
s
Is there any difference on the call site aside from doing this:
Copy code
val viewState by viewModel.viewState
instead of this?
Copy code
val viewState by viewModel.viewState.collectAsState()
f
Yes if you don't want the whole state but need only a part of it. But I guess that depends on your style of coding. E.g
Copy code
val viewState by viewModel.viewState.collectAsState()
val isLoading = viewState.isLoading
val error = viewState.error
You should use the thing that most suits your project and codestyle 🤷‍♂️
👍 1
s
Ah shit, you got the official Android devs twitter backing your claim 😅 I’ll still stay grumpy and say I don’t prefer it, but it’s nice for various options to exist.
1