Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing observer on on destroy() android

I am developing for android using android annotations. I have a singleton observable object for which I want to add activity as an observer. Something like as follows:

@EActivity(R.layout.myActivity)
public class MyActivity extends SherlockActivity implements Observer { 

    @Bean //has singleton scope
    protected Observerable o;

    @Override
    public void onCreate() {
        o.registerObserver(this);
    }

    @Override
    public void onDestroy() {
        o.unregisterObserver(this);
    }

    //more code

My question lies with the on destroy method. Will there be a situation where android kills the activity during a stopped or paused state without calling onDestroy()? If this is the case my Observerable could be keeping a live reference to an activity that is no longer used by the system, which is not good. Or is this not the case? If it is my presumption would be to keep weak references to all my activities in my list of registered observers, so they can be unregistered automatically. Is this a good solution or is it not needed?

like image 733
mogronalol Avatar asked Mar 07 '26 09:03

mogronalol


1 Answers

The OS can kill your process without calling onDestroy, but otherwise you can rely on onDestroy being called. So provided your Observable is in the same process as the activity, you're fine.

like image 144
Tom Mulcahy Avatar answered Mar 08 '26 23:03

Tom Mulcahy