Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to start executing a block of code after changing the value of LiveData when using .observeAsState()?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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(...) 
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading