观察者模式优化

观察者模式,只听别人讲不太容易理解,要自己深入,慢慢学习它的精妙之处!

调用

public void test(){
        Observable.create(new ObservableOnSubscribe() {
            @Override
            public void subscribe(Emitter emitter) {
                emitter.onNext("ddddd");
            }
        }).subscribeObserver(new Observer() {
            @Override
            public void onNext(String o) {
                Log.e("chy", o);
            }

            @Override
            public void onSubscribe() {
                Log.e("chy", "onSubscribe");
            }

            @Override
            public void onError(Throwable throwable) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

ObservableOnSubscribe.java接口类

public interface ObservableOnSubscribe {
    void subscribe(Emitter emitter);
}

被观察者ObservableSource.java

public interface ObservableSource {
    void subscribeObserver(Observer observer);
}

被观察者实现类Observable.java

public abstract class Observable implements ObservableSource {
    @Override
    public void subscribeObserver(Observer observer) {
        subscribeActual(observer);
    }

    protected abstract void subscribeActual(Observer observer);


    public static Observable create(ObservableOnSubscribe source){
        return new ObservableCreate(source);
    }
}

被观察者子类ObservableCreate.java

public class ObservableCreate extends Observable {
    public ObservableOnSubscribe source;

    public ObservableCreate(ObservableOnSubscribe observableOnSubscribe){
        this.source = observableOnSubscribe;
    }

    @Override
    protected void subscribeActual(Observer observer) {
        observer.onSubscribe();

        CreateEmitter createEmitter = new CreateEmitter(observer);
        source.subscribe(createEmitter);
    }

    static final class CreateEmitter implements Emitter{

        Observer observer;

        public CreateEmitter(Observer observer){
            this.observer = observer;

        }
        @Override
        public void onNext(T t) {
            observer.onNext(t);
        }

        @Override
        public void onError(Throwable throwable) {
            observer.onError(throwable);
        }

        @Override
        public void onComplete() {
            observer.onComplete();
        }
    }
}

观察者Observer.java

public interface Observer {
    void onNext(T t);
    void onSubscribe();
    void onError(Throwable throwable);
    void onComplete();
}

发射者Emitter.java

public interface Emitter {
    void onNext(T t);
    void onError(Throwable throwable);
    void onComplete();
}

你可能感兴趣的:(观察者模式优化)