Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle To Remove/Add Live Data Observer to Observe On Button Click

I want to to observe a row in room database. it change after some period. but when we stop button click it need to be stop observing form database and when click start button it start observing again.

My current code is To create Observer

    private lateinit var recordObserver: Observer<Ride>

    recordObserver= Observer<Ride> { rides ->

                    if (rides != null) 

                        updateData(rides)

                    else
                        setDataToZero()
                } 

when(isState){
     Constants.isrunning->{//need to start observer}
     Constants.Stop->{//need to stop observer}
}
like image 669
Bilal Yasin Avatar asked Nov 06 '22 09:11

Bilal Yasin


1 Answers

In order to start/stop observing LiveData you should use observe() / removeObserver() methods. As simple as that. If you have access to LifecycleOwner (Fragment, Activity) use fun observe(), if not - use fun observeForever().

Your code will look like this:

val liveData = database.observeRides()  // get your live data
when(isState){
    Constants.isrunning -> { 
        liveData.observe(this, recordObserver) 
    }
    Constants.Stop -> {
        liveData.removeObserver(recordObserver) 
    }
}
like image 124
Demigod Avatar answered Dec 04 '22 13:12

Demigod