I’m trying to use ViewModel + LiveData, as seen <h...
# compose
b
I’m trying to use ViewModel + LiveData, as seen https://developer.android.com/jetpack/compose/interop#viewmodel however the code sample (in thread reply) always shows null
Copy code
@Composable
fun LegalBodyContent(contentPadding: InnerPadding = InnerPadding(), onLegal: () -> Unit) {
  val viewModel: MyViewModel = viewModel()
  val user = viewModel.user.observeAsState()
  Text(text = "${user.value}")
}


class MyViewModel: ViewModel() {
  private val userId: LiveData<String> = MutableLiveData()
  val user = userId.switchMap { id ->
    liveData {
      while(true) {
        emit("Test string")
        delay(30_000)
      }
    }
  }
}
s
Do you set
userId
value anywhere ?
b
I thought that
emit("Test string")
, would set it?
s
With switchMap you are mapping the value received in userId to whatever livedata returned in the block
b
Right and that doesn’t happen on the initial initialization
So to kick off say a network request, would I need to use onCommit to then call a method on the view model to do that?
s
If there's not value in userId, you won't map anything and thus won't have anything in user
It depends where you're getting the userId from.
b
At the moment I’m using a single activity for the entire UI of my app using https://github.com/zsoltk/compose-router
s
Ask yourself the right questions: - How can I get my current userId ? - With this userId how can I get my user ? I'm not sure you need to use a livedata for the userId. You could just use
val user = livedata{}
And load and emit your user inside the livedata block.
b
Ah sorry, what I was aiming to do was to load data (using Fuel) in a few of my compose functions that represent different screens. A lot of the examples I saw used multiple activities.
s
If you just want to learn and play with compose maybe find some simpler use cases. The codelabs are good starting points. You can also take a look at Google samples (or any other sample you can find in this channel) if you need help with your app architecture.
b
I think the Android Compose examples (on Github) all used either multiple activities / fragments. Thanks for your help 🙂