首页 > 其他 > 详细

使用LiveData处理事件

时间:2018-09-20 00:05:06      阅读:285      评论:0      收藏:0      [点我收藏+]

今天遇到了一件奇怪的事情,在同事手机上有个Activity(A)关闭后竟然又被创建了,调试后发现原来每次关闭这个Activity(A)都会触发上一个Activity(B)的生命周期改变,然后在订阅的LiveData对象会收到OnChange消息创建Activity(A),正常情况下,这种数据我们只需要处理一次,准确的来讲就是事件,这种情况下我们可以使用下面的SingleLiveEvent来处理。

package com.example.android.architecture.blueprints.todoapp;
 
import android.arch.lifecycle.LifecycleOwner;
import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.Observer;
import android.support.annotation.MainThread;
import android.support.annotation.Nullable;
import android.util.Log;
 
import java.util.concurrent.atomic.AtomicBoolean;
 
/**
 * A lifecycle-aware observable that sends only new updates after subscription, used for events like
 * navigation and Snackbar messages.
 * <p>
 * This avoids a common problem with events: on configuration change (like rotation) an update
 * can be emitted if the observer is active. This LiveData only calls the observable if there‘s an
 * explicit call to setValue() or call().
 * <p>
 * Note that only one observer is going to be notified of changes.
 */
public class SingleLiveEvent<T> extends MutableLiveData<T> {
 
    private static final String TAG = "SingleLiveEvent";
 
    private final AtomicBoolean mPending = new AtomicBoolean(false);
 
    @MainThread
    public void observe(LifecycleOwner owner, final Observer<T> observer) {
 
        if (hasActiveObservers()) {
            Log.w(TAG, "Multiple observers registered but only one will be notified of changes.");
        }
 
        // Observe the internal MutableLiveData
        super.observe(owner, new Observer<T>() {
            @Override
            public void onChanged(@Nullable T t) {
                if (mPending.compareAndSet(true, false)) {
                    observer.onChanged(t);
                }
            }
        });
    }
 
    @MainThread
    public void setValue(@Nullable T t) {
        mPending.set(true);
        super.setValue(t);
    }
 
    /**
     * Used for cases where T is Void, to make calls cleaner.
     */
    @MainThread
    public void call() {
        setValue(null);
    }
}

 

使用LiveData处理事件

原文:https://www.cnblogs.com/Potato-Eater/p/9678193.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!