美文网首页
SingleLiveEvent

SingleLiveEvent

作者: lhl_012 | 来源:发表于2020-01-03 13:40 被阅读0次

LiveData多次收到消息,方案来自Stackoverflow某位Google工程师

import androidx.annotation.MainThread;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;

import java.util.concurrent.atomic.AtomicBoolean;

public class SingleLiveEvent<T> extends MutableLiveData<T> {
    private final AtomicBoolean mPending = new AtomicBoolean(false);
    @Override
    public void observe(@NonNull LifecycleOwner owner, @NonNull final Observer<? super T> observer) {
        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);
    }
}

相关文章

  • SingleLiveEvent

    LiveData多次收到消息,方案来自Stackoverflow某位Google工程师

  • SingleLiveEvent

    #### 只要使用过一段时间的LiveData就会发现,LiveData会经常多次回调数据。我们经常碰到的这个问题...

  • SingleLiveEvent

    SingleLiveEvent解决LiveData或者MutableLiveData多次回调的问题[http://...

  • 记一次LiveData重复触发数据回调

    我用的是网上大哥的SingleLiveEvent,完美解决,附源码 public class SingleLive...

  • Android SingleLiveEvent解决Mutable

    一、前言 只要使用过一段时间的LiveData就会发现,LiveData会经常多次回调数据。我们经常碰到的这个问题...

网友评论

      本文标题:SingleLiveEvent

      本文链接:https://www.haomeiwen.com/subject/ggyzoctx.html