livedata的妙用
public final class LiveEventBus {
private final Map>bus;
? ? private LiveEventBus() {
bus =new HashMap<>();
? ? }
private static class SingletonHolder {
private static final LiveEventBusDEFAULT_BUS =new LiveEventBus();
? ? }
public static LiveEventBusget() {
return SingletonHolder.DEFAULT_BUS;
? ? }
public synchronized Observablewith(String key, Class type) {
if (!bus.containsKey(key)) {
bus.put(key, new BusLiveEvent<>());
? ? ? ? }
return (Observable)bus.get(key);
? ? }
public Observablewith(String key) {
return with(key, Object.class);
? ? }
public interface Observable {
void setValue(T value);
? ? ? ? void postValue(T value);
? ? ? ? void postValueDelay(T value, long delay, TimeUnit unit);
? ? ? ? void observe(@NonNull LifecycleOwner owner, @NonNull Observer observer);
? ? ? ? void observeSticky(@NonNull LifecycleOwner owner, @NonNull Observer observer);
? ? ? ? void observeForever(@NonNull Observer observer);
? ? ? ? void observeStickyForever(@NonNull Observer observer);
? ? ? ? void removeObserver(@NonNull Observer observer);
? ? }
private static class BusLiveEventextends LiveEventimplements Observable {
private class PostValueTaskimplements Runnable {
private ObjectnewValue;
? ? ? ? ? ? public PostValueTask(@NonNull Object newValue) {
this.newValue = newValue;
? ? ? ? ? ? }
@Override
? ? ? ? ? ? public void run() {
setValue((T)newValue);
? ? ? ? ? ? }
}
private HandlermainHandler =new Handler(Looper.getMainLooper());
? ? ? ? @Override
? ? ? ? protected Lifecycle.StateobserverActiveLevel() {
return super.observerActiveLevel();
//? ? ? ? ? ? return Lifecycle.State.STARTED;
? ? ? ? }
@Override
? ? ? ? public void postValueDelay(T value, long delay, TimeUnit unit) {
mainHandler.postDelayed(new PostValueTask(value), unit.convert(delay, unit));
? ? ? ? }
}
}