# compose

Prashant Priyadarshi

10/26/2020, 6:26 AM
Using MutableState vs LiveData in compose For displaying UI using simple variable, say "name" in compose, which of the below options is better ? 1. using state in viewModel : val name = mutableStateOf<String>("") in ui : simply access it as 2. using live data val _name = MutableLiveData<String>("") val displayName ={ it?: "" } in ui : val name = viewModel.displayName.observeAsState("")


10/26/2020, 6:39 AM
Do whatever works better for you. In your example, I'd go with state if it's only going to be used in compose.


10/26/2020, 7:02 AM
My personal opinion, if you already have Flow/Rxjava in the project, I don’t see any reason to use LiveData


10/26/2020, 11:11 AM
Use the State, it's likely to be the default in Compose

Adam Powell

10/26/2020, 2:25 PM
Use mutableStateOf if the data source is hot or flow if the data source is cold and you need subscription lifecycle management. Use LiveData if your existing data source is already offering LiveData and you don't want to change that existing code.
👍 4

Lauren Yew

01/04/2021, 9:12 PM
What's the difference between State and LiveData? (Besides that State is suggested for Compose).

Adam Powell

01/04/2021, 9:44 PM
Snapshot state can notify observers of changes without explicit observer registration, and can do so transitively without that observability needing to be represented in the type system in those middle layers.
Say you have some interface:
Copy code
interface FooCalculator {
  fun calculateFoo(input: T): Foo
and some other class that uses it:
Copy code
class FooUser(
  private val fooCalculator: FooCalculator
) {
  fun doAThingWithAFoo(): Result
No part of this knows about observability of results
But if you supply a
that looks like this:
Copy code
class MyFooCalculator : FooCalculator {
  private val myInternalState by mutableStateOf(initialValue)

  // ...

  override fun calculateFoo(input: T): Foo {
    return doSomeCalculation(myInternalState, input)
then you've introduced observability for code that uses a
with your observable dependency
You can think about deriving state from observable inputs as "regular" code rather than as a chain of functional reactive operators;
.map {}
, etc.
🙏 1