订阅后合并PublishSubject

时间:2017-04-06 08:09:42

标签: java rx-java

这是我想要实现的目标:

PublishSubject<Integer> subject = PublishSubject.create();
    subject.subscribe(new Consumer<Integer>() {
        @Override
        public void accept(@NonNull Integer integer) throws Exception {
            System.out.println("item = " + integer);
        }
    });
    subject.mergeWith(Observable.just(1, 2));
    subject.onNext(3);
    /* 
    expected: 
    item = 1
    item = 2
    item = 3
    but received :
    item = 3
    */

我知道我可以这样做:

PublishSubject.merge(subject, Observable.just(1,2)).subscribe(new Consumer<Integer>() {
        @Override
        public void accept(@NonNull Integer integer) throws Exception {
            System.out.println("item = " + integer); // emits 1 2 3
        }
    });

但问题是用户已经订阅了主题。 我无法找到一种优雅的方式。

修改 由于受试者既是观察者又是订阅者,你可以这样做:

final PublishSubject<Integer> subject = PublishSubject.create();
    subject.subscribe(new Consumer<Integer>() {
        @Override
        public void accept(@NonNull Integer integer) throws Exception {
            System.out.println("item = " + integer);
        }
    });
    Observable.just(1,2).subscribe(subject);
    subject.onNext(3);//subscription
    /*
    expected:
    item = 1
    item = 2
    item = 3
    but received :
    item = 1
    item = 2
    */

1 个答案:

答案 0 :(得分:1)

将代码更改为

header('Content-Type:text/json');
echo json_encode($array);

但是仍然。你需要订阅这个Observable。