Q1: How to use LiveData and the problems to be solved?
A1: LiveData is stated-changing data, internally implemented by “observer” design mode. The theme object is “LifecycleOwner”, and the observer is provided by the working scene that depends on LiveData data.
Initialization:
private LiveData<String> liveData = new MutableLiveData<String>("Initial value") {// Called when the number of active observers change to 1 from 0.
@Override
protected void onActive(a) {
super.onActive();
}
// Called when the number of active observers change from 1 to 0.
@Override
protected void onInactive(a) {
super.onInactive(); }};Copy the code
Speaking of observers, LiveData provides MediatorLiveData to manage multiple LiveData sources if there are multiple topics.
LiveData<Integer> liveData1 = ... ; LiveData<Integer> liveData2 = ... ; MediatorLiveData<Integer> liveDataMerger =new MediatorLiveData<>();
liveDataMerger.addSource(liveData1, value -> liveDataMerger.setValue(value));
liveDataMerger.addSource(liveData2, value -> liveDataMerger.setValue(value));
liveDataMerger.addSource(liveData1, new Observer<Integer>() {
private int count = 1;
{@literal @}Override public void onChanged(@Nullable Integer s) {
count++;
liveDataMerger.setValue(s);
if (count > 10) { liveDataMerger.removeSource(liveData1); }}});Copy the code
There are two modes of observer: lifecycle dependent and permanent.
public void observe(@NonNull LifecycleOwner owner,
@NonNull Observer<? super T> observer) {}public void observeForever(@NonNull Observer<? super T> observer) {}Copy the code
LiveData role:
- You should remove the observer in conjunction with the Android lifecycle state.
- Status data. Provides one-to-many dependencies between objects so that when data changes within LiveData, all its observers can be notified and updated.
Application scenarios
- MVVM engineering structure
Q2: What should be noted in the multi-threaded LiveData scenario?
A2: Because it is related to the life cycle, the main thread is required for observer registration, data update setValue, etc. Non-main thread operations will have assertion errors.
If an asynchronous thread wants to update data, it can use #postValue(also thrown to the main thread).
Q3: What are the implementation methods of LiveData that can be applied in other working scenarios?
A3: There are generally the following points:
-
In concurrent scenarios, you can use SafeIterableMap to safely traverse hash data.
- Not thread-safe, but safe to traverse in concurrency.
- Supports multiple Iterator traversal modes.
package androidx.arch.core.internal;
/**
* LinkedList, which pretends to be a map and supports modifications during iterations.
* It is NOT thread safe.
*
* @param <K> Key type
* @param <V> Value type
* @hide* /
public class SafeIterableMap<K.V> implements 可迭代<Map.Entry<K.V>> {}Copy the code
- A utility class that throws tasks onto the main thread.
ArchTaskExecutor.getInstance().postToMainThread(mPostValueRunnable);
Copy the code