如何修改主题输出类型?

时间:2017-02-02 15:26:05

标签: android rx-java rx-android

我有以下单身人士:

public abstract class Store<Input, Output> {
    private BehaviorSubject<Input> subject = BehaviorSubject.create();
    private Observable<Output> observable; //also a singleton

    public final Subscription register(Subscriber<Output> subscriber) {
        if (observable == null) {
            observable = subject.compose(getTransformer()); //is this hot?
        }
        return observable.subscribe(subscriber);
    }

    public final void unregister(Subscription subscription) { //unregister }

    //applies operators to the original stream to transform Input -> Output
    protected abstract Observable.Transformer<Input, Output> getTransformer();

    public final void onNext(Input event) { subject.onNext(event);}
}

问题:当我旋转设备或最小化应用程序时,可观察到的模具(中止网络执行)。 subject.compose()是否会感冒可观察,如果是,为什么?。

我尝试使用publish.autoConnect() / share()让它变热,现在它不会在轮换时死亡......但是BehaviourSubject会中断。当我旋转设备时,我没有在订阅时获得第一个值。

如何转换subject的输出值并使其表现为subjectSAMPLE PROJECT

LOG:

  

USER:点击按钮从网络中获取
  D:从中检索   网络... D:网络请求成功执行
  D:缓存到记忆中   USER:点击按钮再次从网络获取
  D:从网络中检索...
  USER:按下主页按钮,应用程序背景
  d:.unsubscribe()

1 个答案:

答案 0 :(得分:0)

事实证明,我一直在使用主题错误。这是我想在上面实现的正确版本:

 public abstract class RxStore<Input, Output> {
        private BehaviorRelay<Output> relay;

        public final Subscription register(Subscriber<Output> subscriber) {
            if (relay == null) {
                relay = BehaviorRelay.create(defaultValue());
            }
            return relay.subscribe(subscriber);
        }

        public final void unregister(Subscription subscription) {
            if (subscription != null && !subscription.isUnsubscribed()) {
                subscription.unsubscribe();
            }
        }

        public void execute(Input event) {
            buildObservable(event).subscribe(relay);
        }

        /**
         * @return the first or default value emitted to subscribers
         */
        protected Output defaultValue() {
            return null;
        }

        /**
         * @return an buildObservable responsible of handling its own errors.
         */
        protected abstract Observable<Output> buildObservable(Input event);
    }

编辑:

我发现这种方法非常有用。我正在使用这种方法,我写了一篇关于此的文章:

https://medium.com/@FerRaviola/rxandroid-an-event-bus-on-steroids-9699e93eca98#.tqbxleo4h