Let’s see if we can use it. It’s ridiculously simple. Okay, let’s start here
val getTopTabLiveData by lazy { MutableLiveData<Boolean> ()}... viewModel.getTopTabLiveData.observe(this) {// do some thing
}
Copy the code
What does observer() do
Binds the specified event to the lifecycle
@MainThread
public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer) {
assertMainThread("observe");
// If the life cycle is destroyed, ignore it
if (owner.getLifecycle().getCurrentState() == DESTROYED) return;
// Instance a new lifecycle binding observer
LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
// Determine whether a value has been assigned before, to prevent repeated calls to the code
ObserverWrapper existing = mObservers.putIfAbsent(observer, wrapper);
/ / look at LifecycleBoundObserver isAttachedTo ()
// If the value has been assigned before but is called by a different LifecycleOwner, Google will be awesome if it goes to crash without saying much
if(existing ! =null && !existing.isAttachedTo(owner)) {
throw new IllegalArgumentException("Cannot add the same observer"
+ " with different lifecycles");
}
// If an assignment has been made and the above brake processing is ok, no more processing is done
if(existing ! =null) {
return;
}
// Add an Observer to the current LifecycleOwner that responds to events at various stages of the lifecycle
owner.getLifecycle().addObserver(wrapper);
}
Copy the code
See mObservers. PutIfAbsent:
public V putIfAbsent(@NonNull K key, @NonNull V v) {
Entry<K, V> entry = get(key);
// Returns a value if the given value already exists
if(entry ! =null) return entry.mValue;
// If you don't, you can save it
put(key, v);
// return a null value that does not exist before
return null;
}
Copy the code
See LifecycleBoundObserver:
class LifecycleBoundObserver extends ObserverWrapper implements LifecycleEventObserver {
@NonNull
// Lifecycle manager
final LifecycleOwner mOwner;
// What is there to say
LifecycleBoundObserver(@NonNull LifecycleOwner owner, Observer<? super T> observer) {
super(observer);
mOwner = owner;
}
// It's kind of interesting. If you're active, you can do the right fucking life cycle callback
@Override
boolean shouldBeActive(a) {
return mOwner.getLifecycle().getCurrentState().isAtLeast(STARTED);
}
@Override
public void onStateChanged(@NonNull LifecycleOwner source,
@NonNull Lifecycle.Event event) {
Lifecycle.State currentState = mOwner.getLifecycle().getCurrentState();
// If the life cycle is destroyed, remove the Observer to avoid memory leaks
if (currentState == DESTROYED) {
removeObserver(mObserver);
return;
}
Lifecycle.State prevState = null;
while (prevState != currentState) {
prevState = currentState;
activeStateChanged(shouldBeActive());
currentState = mOwner.getLifecycle().getCurrentState();
}
}
// Determine whether the two lifecycle managers are the same
@Override
boolean isAttachedTo(LifecycleOwner owner) {
return mOwner == owner;
}
@Override
void detachObserver(a) {
mOwner.getLifecycle().removeObserver(this); }}Copy the code
Livedata.observe () has been observed. Go to Livedata.postValue ().
liveData.postValue("a");// Asynchronously pass the value
liveData.setValue("b"); // Synchronize the value
// Result: the value "b" will be set first, then the main thread will overwrite it with the value "a".
If postValue() is called multiple times before the main thread executes postValue(), only the last value will be scheduled
Copy the code
What does postValue() do
What else can you do, damn it, is pass values, that’s the end of the article, no, no, asynchronous pass is worth paying attention to how to handle shared variables in multiple threads
.protected void postValue(T value) {
boolean postTask;
synchronized (mDataLock) {
// Determine if the assignment has already been made
postTask = mPendingData == NOT_SET;
// Assign to mPendingData
mPendingData = value;
}
// Return (); // Return ()
// Hey, mPostValueRunnable doesn't do that, it just prevents the same value from being assigned multiple times by the deadbolt thread
if(! postTask)return;
// Execute the thread on the main threadArchTaskExecutor.getInstance().postToMainThread(mPostValueRunnable); }...// Unassigned state
static final Object NOT_SET = new Object()
// The default state is unassigned
volatile Object mPendingData = NOT_SET
// Pass thread
private final Runnable mPostValueRunnable = new Runnable() {
@SuppressWarnings("unchecked")
@Override
public void run(a) {
// All values are passed through newValue
Object newValue;
synchronized (mDataLock) {
newValue = mPendingData;
// Return to default unassigned state
mPendingData = NOT_SET;
}
// All roads lead to setValuesetValue((T) newValue); }};Copy the code
setValue()
What’s there to say, the other shot, I’m the core code for transmitting data, okay, shit,dispatchingValue
// Set data transfer. If there are active ObserverWrapper(observers), the value will be distributed to them.
protected void setValue(T value) {
assertMainThread("setValue");
mVersion++;
mData = value;
dispatchingValue(null);
}
@SuppressWarnings("WeakerAccess") /* synthetic access */
void dispatchingValue(@Nullable ObserverWrapper initiator) {
// Determine whether event distribution is already underway, if so, interrupt
if (mDispatchingValue) {
mDispatchInvalidated = true;
return;
}
// Event distribution begins
mDispatchingValue = true;
do {
mDispatchInvalidated = false;
if(initiator ! =null) {
considerNotify(initiator);
initiator = null;
} else {
for (Iterator<Map.Entry<Observer<? super T>, ObserverWrapper>> iterator =
mObservers.iteratorWithAdditions(); iterator.hasNext(); ) {
considerNotify(iterator.next().getValue());
if (mDispatchInvalidated) break; }}}while (mDispatchInvalidated);
// End of event distribution
mDispatchingValue = false; }...private void considerNotify(ObserverWrapper observer) {
// If the lifecycle manager has been destroyed, ignore it
if(! observer.mActive) {return;
}
// Check the initial state before distribution, if not active, do not change the state
if(! observer.shouldBeActive()) { observer.activeStateChanged(false);
return;
}
// Determine version, because from above, each assignment of version becomes
/ / fuck, so as not to fall into multiple distribution, ensure that only the value of the first
if (observer.mLastVersion >= mVersion) {
return;
}
observer.mLastVersion = mVersion;
// Perform event distribution for each lifecycle manager's observer
observer.mObserver.onChanged((T) mData);
}
Copy the code
Did you get it?