Using MutableState vs LiveData in compose For disp...
# compose
p
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 viewModel.name 2. using live data val _name = MutableLiveData<String>("") val displayName = Transformations.map(_name){ it?: "" } in ui : val name = viewModel.displayName.observeAsState("")
s
Do whatever works better for you. In your example, I'd go with state if it's only going to be used in compose.
g
My personal opinion, if you already have Flow/Rxjava in the project, I don’t see any reason to use LiveData
w
Use the State, it's likely to be the default in Compose
a
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
l
What's the difference between State and LiveData? (Besides that State is suggested for Compose).
a
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
FooCalculator
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
FooUser
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
572 Views