So, I have a Composable with a VM and I would like...
# compose
j
So, I have a Composable with a VM and I would like to send a callback to the parent composable when something happens in the VM... something like
Copy code
@Composable
fun FunA(onResult : (Result) -> Unit){
  val vm by viewModels...
  val resultState by viewModel.onResult.observeAsState()
  val result = resultState
  if (result != null) {
        onResult(result)
  }
  val state = vm.state.observeAsState()
  
}
but I don't want to call
onResult
at every composition, only when
onResult
changes... Any idea of how to implement that ?
c
I think this is maybe a good candidate for something to be modelled as state? see: https://developer.android.com/topic/architecture/ui-layer/events
2023-04-25 at 08.55.46.png
but i dont understand your use case 100%, so maybe its not the right answer. but when my VM typically does some operation... i want to update some state to signify that that operation succeeded, etc. and the compose layer just observes that and draws it or uses a LaunchedEffect to do something (like navigate) thats actually the example they show in the docs above. on successful login... you dont just send an event back to the composable. you instead update some state, and the composable observes that..
z
I feel like you’re putting too much business logic in the compose world. You can have the parent compose be notified through your ViewModel as well. Hoisting state out of this child composable which uses a magic ViewModel makes little sense
m
Also, you don’t want the “onResult” out in open like that. It’s a side effect that belongs in some sort of side effect block. To be honest i would use a LaunchedEffect. Otherwise you’re going to be sending the callback on every recomposition.
Copy code
LaunchedEffect(viewModel.onResult.observeAsState()) {
    result?.let { onResult(it) }
}
j
Thank you all , I learned a lot 😁
I sent a null value to the LiveData so the next state change will not trigger the callback... But I still don't understand the need of using LaunchedEffect
c
long but good.

https://www.youtube.com/watch?v=CQzuFZjiUMs

manuel vivo talks about how "events" should be treated. he wrote/helped write the guide i linked to earlier.