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

Joseph D

11/20/2020, 10:25 PM
Hi there. In the case of this

example

, at which stage would you call
chatVm.getMessages()
?
j

Jeisson Sáchica

11/20/2020, 10:53 PM
I usually trigger this type of resource loading right at the init block of the ViewModel, but if you want more control you could also do it when your @Composable first creates using the onActive { chatVm.loadMessages() } (which the docs say it is practically just a onCommit(true) { chatVm.loadMessages() })
If you are using navigation you could also do it when your screen is created:
Copy code
NavHost(navController = navController, startDestination = "chat") {
  // Other routes
  composable("chat") {
    val chatVm: ChatViewModel by viewModels()
    chatVm.loadMessages()
    val msgs by chatVm.messages.observeAsState()
    ChatScreen(messages = msgs)
  }
}
j

Joseph D

11/20/2020, 11:02 PM
TIL
onActive
. Thanks a lot.
3 Views