What should be paid attention to when using Android LiveData

  • 2021-12-11 19:05:15
  • OfStack

Directory 1. Callback notification 2. Data backflow 3. Event wrapper

Refer to the official document developer. android. com/topic/libra for information on what LiveData is and how it is basically used

Simply put, LiveData is an observable data container class. It wraps the data so that the data becomes the "observer" and the page becomes the "observer". When ViewModel storage pages need a variety of data changes, through the way of LiveData to realize the notification of the page, complete the communication between ViewModel and page components.

Then when using it, it is found that there are the following places to pay attention to:

1. Callback notifications

Observers of LiveData receive a callback every time they enter an active state. If they only want to receive a callback once, they can use SingleLiveEvent. Note that SingleLiveEvent is limited to one observer. If more than one is added, only one will be called, and there is no guarantee of which one.

2. Data backflow

The so-called data backflow is an image statement, which means that setValue/postValue first, then observe (new Obs ()) is called, and a callback is received. Then call observe (new anotherObs ()), if you can still receive the first callback, that is, the old data. The solution can refer to the open source project: UnPeek-LiveData.

3. Event wrapping

As mentioned above, SingleLiveEvent is limited to one observer. If multiple observers are needed, the solution is to use event wrappers. Defines a data wrapper, which internally judges whether the event is consumed or not, and no callback notification will be made after being consumed. The code is as follows:


/**
*  Event wrapper, which explicitly manages whether an event has been handled 
* @param <T> ViewModel Data in, such as:  
* MutableLiveData<LiveEventWrapper<String>>()
*/
public class LiveEventWrapper<T> {

  private T content;
  private boolean hasBeenHandled;

  public LiveEventWrapper(T content) {
    this.content = content;
  }

  /**
   * Returns the content and prevents its use again.
   */
  public T getContentIfNotHandled() {
    if (hasBeenHandled) {
      return null;
    } else {
      hasBeenHandled = true;
      return content;
    }
  }

  /**
   * Returns the content, even if it's already been handled.
   */
  public T peekContent() {
    return content;
  }

  public boolean isHasBeenHandled() {
    return hasBeenHandled;
  }

}

Or


import androidx.annotation.NonNull;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;

public class CleanLiveData<T> extends LiveData<T> {
  private boolean hasModified = false;

  @Override
  public void observe(@NonNull LifecycleOwner owner, @NonNull final Observer<? super T> observer) {
    super.observe(owner, new Observer<T>() {
      private boolean hasIntercept = false;

      @Override
      public void onChanged(T t) {
        if (!hasModified || hasIntercept) {
          observer.onChanged(t);
        }
        hasIntercept = true;
      }
    });
  }

  @Override
  public void observeForever(@NonNull final Observer<? super T> observer) {
    super.observeForever(new Observer<T>() {
      private boolean hasIntercept = false;

      @Override
      public void onChanged(T t) {
        if (!hasModified || hasIntercept) {
          observer.onChanged(t);
        }
        hasIntercept = true;
      }
    });
  }

  @Override
  public void setValue(T value) {
    super.setValue(value);
    hasModified = true;
  }

  @Override
  public void postValue(T value) {
    super.postValue(value);
    hasModified = true;
  }

}

To sum up, the above phenomena are basically caused by the viscous characteristics of LiveData, so when using LiveData, we must understand its concept and principle.

The above is the Android LiveData need to pay attention to the details of the use of Android LiveData, more information about the use of Android please pay attention to other related articles on this site!


Related articles: