Is there any problem if I use something like below...
# compose
r
Is there any problem if I use something like below in viewModel
Copy code
val name = mutableStateOf("")
instead of using this and viewmodel.name.observeAsState("") in UI.
Copy code
private val _name = MutableLiveData("")
val name: LiveData<String> = _username
c
No, totally fine. You just might do something like
Copy code
var name by mutableStateOf(“”)
  private set
to be able to manipulate the
name
only from your view model.
1
o
As for me the second approach is better, as it keeps your ViewModel compose-independent.
a
Snapshots are orthogonal to other compose mechanisms and it's fine to use them elsewhere. LiveData adds far more restrictions than a snapshot dependency does, plus you lose the transactional consistency across different snapshot state objects if you use LiveData instead
c
You can use
StateFlow
or
SharedFlow
in your view model to use kotlin coroutines dependent types instead of
LiveData
.
a
You also lose that consistency if you use StateFlow
You can use and observe snapshots without any other compose mechanisms (without the compiler plugin too). It does not affect testability or viability of the same code elsewhere.
See
snapshotFlow {}
for an example
r
Thanks, everyone. I will definitely check on snapshotFlow{} @Adam Powell. Though I am confused about many things. I hope I will be able to follow the best practice.
c
I usually have ViewModel and Model where the model and expose StateFlow or SharedFlow as needed. The snapshotFlow looks like a powerful mechanism for dealing with state change and exception handling in the ViewModel.
r
I have a one-shot operation from the network. Not like there will be a flow of data over time. Every time I call I get a fixed amount of data. Do you think Flow will bring additional help in this scenario?
c
Flow, StateFlow and SharedFlow as kotlin stdlib so it will work anywhere. LiveData is Android specific. I'm interested in making my core business logic independent of the UI technology even from Compose.
👍 1
a
As I explained above, snapshots are independent of the UI technology. That it's distributed along with the compose-runtime artifact is an implementation detail, compose-runtime is itself independent of UI technologies such as compose-ui, and any tree-shaking build tool such as proguard that removes unused code from your final artifacts will omit the rest of compose-runtime if snapshots are all you use.
t
You also lose that consistency if you use StateFlow
Could we expand upon this a bit more? This is interesting because
*Flow
APIs have been in line to replace
LiveData
in presentation land; I wonder if the snapshot state system is similarly poised as a replacement for
*Flow
in presentation land?
1