美文网首页
封装LiveData实现跨界面处理消息

封装LiveData实现跨界面处理消息

作者: 一个没有梦想的IT男 | 来源:发表于2020-05-26 11:59 被阅读0次

    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));

            }

    }

    }

    相关文章

      网友评论

          本文标题:封装LiveData实现跨界面处理消息

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