Usage of Android Lifecycle Architecture Components

  • 2021-08-21 21:27:50
  • OfStack

Support Library 26.1 + directly supports the lifecycle architecture component. With this component, the nightmare of Android life cycle has become a thing of the past. There is no need to worry about Can not perform this action after onSaveInstanceState.

The author encapsulates a helper class that simplifies the use of this component, which is about 70 lines of code:


public class LifecycleDelegate implements LifecycleObserver {
  private LinkedList<Runnable> tasks = new LinkedList<>();
  private final LifecycleOwner lifecycleOwner;
  public LifecycleDelegate(LifecycleOwner lifecycleOwner) {
    this.lifecycleOwner = lifecycleOwner;
    lifecycleOwner.getLifecycle().addObserver(this);
  }
  public void scheduleTaskAtStarted(Runnable runnable) {
    if (getLifecycle().getCurrentState() != Lifecycle.State.DESTROYED) {
      assertMainThread();
      tasks.add(runnable);
      considerExecute();
    }
  }
  @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
  void onStateChange() {
    if (getLifecycle().getCurrentState() == Lifecycle.State.DESTROYED) {
      tasks.clear();
      getLifecycle().removeObserver(this);
    } else {
      considerExecute();
    }
  }
  void considerExecute() {
    if (isAtLeastStarted()) {
      for (Runnable task : tasks) {
        task.run();
      }
      tasks.clear();
    }
  }
  boolean isAtLeastStarted() {
    return getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.STARTED);
  }
  private Lifecycle getLifecycle() {
    return lifecycleOwner.getLifecycle();
  }
  private void assertMainThread() {
    if (!isMainThread()) {
      throw new IllegalStateException("you should perform the task at main thread.");
    }
  }
  static boolean isMainThread() {
    return Looper.getMainLooper().getThread() == Thread.currentThread();
  }
}

Use this in Activity or Fragment


private LifecycleDelegate lifecycleDelegate = new LifecycleDelegate(this);

Then call at the appropriate time lifecycleDelegate.scheduleTaskAtStarted

This worker class checks whether it is called on the main thread to ensure thread safety and update UI on the main thread.

Summarize


Related articles: