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

Brett Best

09/08/2020, 8:23 AM
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

satyan

09/08/2020, 8:47 AM
Do you set
userId
value anywhere ?
b

Brett Best

09/08/2020, 8:48 AM
I thought that
emit("Test string")
, would set it?
s

satyan

09/08/2020, 8:49 AM
With switchMap you are mapping the value received in userId to whatever livedata returned in the block
b

Brett Best

09/08/2020, 8:50 AM
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

satyan

09/08/2020, 8:51 AM
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

Brett Best

09/08/2020, 8:52 AM
At the moment I’m using a single activity for the entire UI of my app using https://github.com/zsoltk/compose-router
s

satyan

09/08/2020, 8:56 AM
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

Brett Best

09/08/2020, 8:57 AM
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

satyan

09/08/2020, 8:58 AM
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

Brett Best

09/08/2020, 8:59 AM
I think the Android Compose examples (on Github) all used either multiple activities / fragments. Thanks for your help 🙂
3 Views