https://kotlinlang.org logo
#compose
Title
# compose
a

Ashu

01/27/2022, 10:17 AM
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

Filip Wiesner

01/27/2022, 10:23 AM
Both have advantages and disadvantages. We ended up using State<UiState> in our app but you might have different needs.
a

Ashu

01/27/2022, 10:34 AM
@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

Filip Wiesner

01/27/2022, 10:41 AM
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

Ashu

01/27/2022, 10:53 AM
@Filip Wiesner cool, will look into that. thanks
s

Stylianos Gakis

01/27/2022, 11:23 AM
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

Filip Wiesner

01/27/2022, 11:33 AM
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

Stylianos Gakis

01/27/2022, 11:39 AM
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

Filip Wiesner

01/27/2022, 11:44 AM
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

Stylianos Gakis

01/28/2022, 3:01 PM
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