Alex G
Alex G

Reputation: 317

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);
        });

    }
}

Upvotes: 16

Views: 20600

Answers (5)

Maiko Trindade
Maiko Trindade

Reputation: 3049

Since @OnLifecycleEvent is deprecated, I believe the best approach would be to implement LifecycleObserver and override lifecycle methods:

class TestObserver: LifecycleObserver {

    override fun onCreate(owner: LifecycleOwner) {
        super.onCreate(owner)
        // your code
    }

    override fun onResume(owner: LifecycleOwner) {
        super.onResume(owner)
        // your code
    }
}

Upvotes: 2

Ray Yuan Liou
Ray Yuan Liou

Reputation: 11

The official documentation of Abhishek Kumar's answer comes from here:

https://developer.android.com/reference/androidx/lifecycle/Lifecycle#subclasses-direct:~:text=Observer%20methods%20can%20receive%20zero%20or%20one%20argument

Here is the document itself:

Observer methods can receive zero or one argument. If used, the first argument must be of type LifecycleOwner.

Methods annotated with Lifecycle.Event.ON_ANY can receive the second argument, which must be of type Lifecycle.Event.

 class TestObserver implements LifecycleObserver {
   @OnLifecycleEvent(ON_CREATE)
   void onCreated(LifecycleOwner source) {}
   @OnLifecycleEvent(ON_ANY)
   void onAny(LifecycleOwner source, Event event) {}
 }

Upvotes: 1

Abhishek Kumar
Abhishek Kumar

Reputation: 4808

Observer methods can receive zero or one argument. If used(means you can go with zero argument too but IFF arguments are used), the first argument must be of type LifecycleOwner. Methods annotated with Lifecycle.Event.ON_ANY can receive the second argument, which must be of type Lifecycle.Event.

class TestObserver implements LifecycleObserver {
         @OnLifecycleEvent(ON_CREATE)
         void onCreated(LifecycleOwner source) {
               //one argument possible
              }
         @OnLifecycleEvent(ON_START)
         void onCreated() {
              //no argument possible
             }
         @OnLifecycleEvent(ON_ANY)
         void onAny(LifecycleOwner source, Event event) {
             //two argument possible only for ON_ANY event
             }
}

Upvotes: 4

jaychang0917
jaychang0917

Reputation: 1888

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){
        ... 
    }
}

Upvotes: 17

Chris
Chris

Reputation: 2362

You shouldn't need to implement your own LifecycleRegistry - just use the one available from AppCompatActivity

public class MainActivity extends AppCompatActivity {
  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

      setContentView(R.layout.activity_main);

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

      getLifecycle().addObserver(new MyLifecycleObserver());
  }
}

If you separate the startFirebase call and the viewmodel observer you can observe the changes from the viewmodel directly in the fragment, i.e.

MyLifecycleObserver starts the firebase call when ON_START is emitted.

public class MyLifecycleObserver implements LifecycleObserver {
    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    public void onStartListener(){
        FirebaseMassage.startFirebase();
    }
}

MainFragment observes the ViewModel directly.

public class MainFragment extends Fragment {

  @Override
  public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
      super.onViewCreated(view, savedInstanceState);
      massageViewModel.getMassage().observe(this, textMassage -> {
          FirebaseMassage.updateFirebaseMassage(textMassage);
      });
  }

Upvotes: 3

Related Questions