Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

    }
}
like image 638
Alex G Avatar asked Aug 22 '18 19:08

Alex G


People also ask

What is LifeCycleOwner?

ProcessLifecycleOwner. Class that provides lifecycle for the whole application process. A class that has an Android lifecycle. These events can be used by custom components to handle lifecycle changes without implementing any code inside the Activity or the Fragment.

How do you use LifeCycleOwner?

LifecycleOwner is a single method interface that denotes that the class has a Lifecycle . It has one method, getLifecycle() , which must be implemented by the class. If you're trying to manage the lifecycle of a whole application process instead, see ProcessLifecycleOwner .

How can you make a class lifecycle aware?

Some Android components like LiveData are already lifecycle-aware. In addition, it is possible to configure any class to be lifecycle-aware by implementing the LifecycleObserver interface within the class.

What is LifecycleObserver?

LifeCycleObserver is part of Google released Android Jetpack LifeCycle Architecture components, and it is an interface that allows you to observe a LifeCycle-aware observable component, typically a LifeCycleOwner (Activity/Fragment), in order to interact with the LifeCycle events and states associated to this component ...


Video Answer


4 Answers

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){
        ... 
    }
}
like image 95
jaychang0917 Avatar answered Oct 16 '22 05:10

jaychang0917


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);
      });
  }
like image 41
Chris Avatar answered Oct 16 '22 05:10

Chris


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
             }
}
like image 3
Abhishek Kumar Avatar answered Oct 16 '22 06:10

Abhishek Kumar


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
    }
}
like image 2
Agna JirKon Rx Avatar answered Oct 16 '22 07:10

Agna JirKon Rx