MohMah MohMah - 6 months ago 26
Android Question

Add and remove RealmChangeListener in View

Is it a good idea to do this in a view that is going to be used in a

RecyclerView
?

@Override protected void onAttachedToWindow(){
super.onAttachedToWindow();
realmResult.addChangeListener(myChangeListener);
}

@Override protected void onDetachedFromWindow(){
super.onDetachedFromWindow();
realmResult.removeChangeListener(myChangeListener);
}


what if the view is used outside a
RecyclerView
and is not recycled?

Answer

According to this Activity methods:onCreate() and onDestroy()

onDetachedFromWindow() is called after onDestroy() which means you are calling methods on a RealmResults that could have been closed. So unless you add more safety checks it could crash.

Doing this would be safe though:

@Override protected void onDetachedFromWindow(){
    super.onDetachedFromWindow();
    if (realmResults.isValid()) {
      realmResult.removeChangeListener(myChangeListener);
    }
}