What is lifecycle observer and how to use it correctly?

心不动则不痛 提交于 2019-12-22 07:02:01

问题


I have read about new architectural components in Android. So, i wanted to ask what are lifecycle observers and why do we need them? In what cases it is useful? Thanks for your answer!


回答1:


You can use ProcessLifecycleOwner for Applications LifeCycle Event. You can implement Lifecycler Observer in your Application Class

public class MyApplication extends MultiDexApplication implements LifecycleObserver

@Override
public void onCreate() {
    super.onCreate();

    ProcessLifecycleOwner.get().getLifecycle().addObserver(this);

}

// Add Lifecycle method to see app background and foreground event

@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void appInResumeState() {
    Toast.makeText(this,"In Foreground",Toast.LENGTH_LONG).show();
}

@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void appInPauseState() {
    Toast.makeText(this,"In Background",Toast.LENGTH_LONG).show();
}

// Add in build.gradle file

implementation 'android.arch.lifecycle:extensions:1.1.1'

//Also In Activities or Fragment

Use can also use them to reduce the complexity of code by creating different component which are implementing lifecycle observer and then pass the lifecycle of activity to these components. This way you can split the huge complexity to different components.

class MainActivity : AppCompatActivity() ,LifecycleObserver{

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        ReduceComplexComponent().registerLifecycle(lifecycle)

    }

}

class ReduceComplexComponent : LifecycleObserver{

    registerLifecycle(lifecycle : Lifecycle){
       lifecycle.addObserver(this)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun resume() {
       Log.d("OnResume","ON_RESUME")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun pause() {
       Log.d("onPause","ON_PAUSE")
    }
}

This way you can listen to activity or fragment lifecycle event in separate components.

We can also manually fetch the current state of our lifecycle instance in Activity and that we can do by using its getCurrentState()

A State also has an isAtLeast() method that we can use to perform comparisons against the current lifecycle state




回答2:


May be a little late to the party, but another nice use-case of lifecycles (except for the obvious ViewModel stuff), is to let many components of the app un-register themselves when the relevant activity is getting destroyed, or simply out of screen.

For example, I have a static factory that creates dialogs, and using lifecycle I can dismiss the dialogs without cluttering the host activity with the old stuff like Dialog mDialog = ... and void onPause(){ ... if (mDialog !null && mDialog.isShowing()) mDialog.cancel() }

Some code:

DialogUtils.java:

public static void showConfirmDialog(Lifecycle lifecycle, String title, String msg, Runnable okRunnable) {
    AlertDialog dialog = AlertDialog.Builder(mAppContext)
    /* configuration stuff ... */
        .build();

    dialog.show();

    lifecycle.addObserver(new LifecycleObserver() {
          @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
          public void cancelDialog() {
            if (dialog.isShowing()) { // if not already dismissed by main-button tap 
              dialog.cancel();
            }
          }
    });
}

MyActivity.java:

public class MyActivity extends AppCompatActivity {

    /* stuff... onCreate()... other stuff... */

    private void confirmDeleteUser(User user){
        DialogUtils.showConfirmDialog(
            MyActivity.this.getLifecycle(), // all activities & fragment have lifecycles
            "Confirm Delete",
            "Action cannot be undone. Sure to continue?",
            new Runnable() { /* stuff... */ }
        );
        // Voilà! 
        // activity no needs to store reference to the dialog and cancel manually on pause
        // it's a fire-and-forget action
    }
}



回答3:


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; so you can monitor foreground and background lifeCycle events.

Here are some useful links with typical usage

  • https://developer.android.com/reference/android/arch/lifecycle/Lifecycle.html
  • https://medium.com/@MinaSamy/android-architecture-components-lifecycle-433ace1ec05d
  • https://riggaroo.co.za/android-architecture-components-looking-lifecycles-part-3/
  • https://proandroiddev.com/make-your-custom-view-lifecycle-aware-its-a-piece-of-cake-90b7c0498686


来源:https://stackoverflow.com/questions/52369540/what-is-lifecycle-observer-and-how-to-use-it-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!