How to start executing a block of code after changing the value of LiveData when using .observeAsState()?
Example: LivaData changes and after need to call Toast.
CodePudding user response:
Showing a Toast is a side effect, so you need to put it inside a LaunchedEffect. Make the LiveData state the key of the LaunchedEffect. This causes the side effect to only occur when this particular LiveData's value changes.
val myDataState = remember { someLiveData.observeAsState() }
LaunchedEffect(myDataState) {
// show the toast
}
Read about it in the documentation here.
CodePudding user response:
If you are using Jetpack Compose then the composable, which observes LiveData as state, will be recomposed each time the state changes.
The thing is that compose provides us with automatic recomposition when it has some kind of changeable state of type State<T>
.
Recomposition means that your composable function will be called again.
liveData.observeAsState()
converts livedata with type T
to an object of type State<T>
It means that you can do something like this:
@Composable
fun MyMethod() {
val data by liveData.observeAsState()
...
Toast.makeText(...)
}