16

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

    }
}
Alex G
  • 317
  • 3
  • 4
  • 11

5 Answers5

17

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){
        ... 
    }
}
jaychang0917
  • 1,880
  • 1
  • 16
  • 21
  • 1
    `@OnLifecycleEvent` is deprecated. https://developer.android.com/jetpack/androidx/releases/lifecycle#2.4.0-beta01 – Akito Nov 19 '21 at 17:49
4

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
             }
}
Abhishek Kumar
  • 4,532
  • 5
  • 31
  • 53
  • Could you provide a link where this is documented? – pallgeuer Oct 11 '20 at 15:01
  • @pallgeuer https://developer.android.com/topic/libraries/architecture/lifecycle#lc – Abhishek Kumar Oct 11 '20 at 16:46
  • Thanks. I was specifically looking for the documentation that the LifecycleOwner can optionally be passed as an argument to the function annotated with OnLifecycleEvent. Is that documented somewhere? – pallgeuer Oct 11 '20 at 16:52
  • `@OnLifecycleEvent` is deprecated. https://developer.android.com/jetpack/androidx/releases/lifecycle#2.4.0-beta01 – Akito Nov 19 '21 at 17:49
3

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);
      });
  }
Chris
  • 2,332
  • 1
  • 14
  • 17
  • `@OnLifecycleEvent` is deprecated. https://developer.android.com/jetpack/androidx/releases/lifecycle#2.4.0-beta01 – Akito Nov 19 '21 at 17:49
2

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
    }
}
Agna JirKon Rx
  • 2,321
  • 2
  • 29
  • 44
1

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) {}
 }
  • `@OnLifecycleEvent` is deprecated. https://developer.android.com/jetpack/androidx/releases/lifecycle#2.4.0-beta01 – Akito Nov 19 '21 at 17:49