Search code examples
androidandroid-lifecycleandroid-architecture-components

How to get LifecycleOwner in LifecycleObserver?


I need to get the LifecycleOwner in an LifecycleObserver to pass it into an ViewModel observer.

This is my MainActivity, were I add the LifecycleObserver.

public class MainActivity extends AppCompatActivity implements LifecycleOwner{

    private LifecycleRegistry mLifecycleRegistry;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.container, MainFragment.newInstance())
                    .commitNow();
        }

        mLifecycleRegistry=new LifecycleRegistry(this);
        mLifecycleRegistry.markState(Lifecycle.State.CREATED);
        getLifecycle().addObserver(new MyLifecycleObserver());
    }


    @NonNull
    @Override
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }

}

And this is my observere, where I need the LifecycleOwner.

public class MyLifecycleObserver implements LifecycleObserver {


    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    public void onStartListener(){

        FirebaseMassage.startFirebase();

        MainFragment.massageViewModel.getMassage().observe(/*here I need the LifecycleOwner*/, textMassage -> {
            FirebaseMassage.updateFirebaseMassage(textMassage);
        });

    }
}

Solution

  • You can just use another signature to get the LifecycleOwner like:

    public class MyLifecycleObserver implements LifecycleObserver {
    
    
        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        public void onStartListener(LifecycleOwner owner){
            ... 
        }
    }