Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Livedata keeps observing even after calling RemoveObserver

Tags:

java

android

RemoveObserver as well RemoveObservers not working . Appreciate some help why this gets called even after i removed the observer after a single call.

public class ABC extends AppCompatActivity{

@Override
protected void onCreate(Bundle savedInstanceState) {

......

db.informationModel.getUserDetails().observe(this, new 
Observer<UserDetailEntity >() {

@Override
public void onChanged(@Nullable UserDetailEntity 
userDetailEntity) {
..... some Code 

db.informationModel.getUserDetails().removeObserver(this);

}
like image 535
Deep Krishna sharma Avatar asked Jun 28 '18 14:06

Deep Krishna sharma


1 Answers

It looks like the code opens separate streams of data each time you call db.informationModel.getUserDetails().

What you need to do is - Store the Observable separately in a variable. Then call observe() and removeObserver() methods on it.

The code will be something like this

public class ABC extends AppCompatActivity{

@Override
protected void onCreate(Bundle savedInstanceState) {

    ......
    final LiveData<UserDetailEntity> userDetailObservable = db.informationModel.getUserDetails();
    userDetailObservable.observe(this, new Observer<UserDetailEntity >() {

        @Override
        public void onChanged(@Nullable UserDetailEntity userDetailEntity) {
            ..... some Code 

            userDetailObservable.removeObserver(this);

        }
    }
}
like image 51
Arushi Pant Avatar answered Nov 16 '22 01:11

Arushi Pant