码迷,mamicode.com
首页 > 其他好文 > 详细

LiveEventBus

时间:2019-08-20 18:43:20      阅读:298      评论:0      收藏:0      [点我收藏+]

标签:setvalue   life   rev   pos   tar   syn   public   简单   jmh   

先简单看看 LiveEventBus 是怎么使用 LiveData 的。

public final class LiveEventBus {

public synchronized <T> Observable<T> with(String key, Class<T> type) {
if (!bus.containsKey(key)) {
bus.put(key, new LiveEvent<>(key));
}
return (Observable<T>) bus.get(key);
}

private class LiveEvent<T> implements Observable<T> {

private final LifecycleLiveData<T> liveData;

LiveEvent(@NonNull String key) {
this.key = key;
this.liveData = new LifecycleLiveData<>();
}

@Override
public void observe(@NonNull final LifecycleOwner owner, @NonNull final Observer<T> observer) {
if (ThreadUtils.isMainThread()) {
observeInternal(owner, observer);
} else {
mainHandler.post(new Runnable() {
@Override
public void run() {
observeInternal(owner, observer);
}
});
}
}

@MainThread
private void observeInternal(@NonNull LifecycleOwner owner, @NonNull Observer<T> observer) {
ObserverWrapper<T> observerWrapper = new ObserverWrapper<>(observer);
observerWrapper.preventNextEvent = liveData.getVersion(http://www.amjmh.com/v/BIBRGZ_558768/) > ExternalLiveData.START_VERSION;
liveData.observe(owner, observerWrapper);
}

@Override
public void post(T value) {
if (ThreadUtils.isMainThread()) {
postInternal(value);
} else {
mainHandler.post(new PostValueTask(value));
}
}

@MainThread
private void postInternal(T value) {
liveData.setValue(value);
}

LiveEventBus

标签:setvalue   life   rev   pos   tar   syn   public   简单   jmh   

原文地址:https://www.cnblogs.com/hyhy904/p/11384644.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!