有人可以向我解释这种行为吗?
我刚学习RxJava,我想将自己的事件发布到Observable链。但是我有一些理解主体行为的问题。
此代码:
PublishSubject<String> subject = PublishSubject.create();
subject.repeat(3)
.subscribe(s -> System.out.println("subject emitted %s", s));
subject.onNext("one");
subject.onNext("two");
subject.onNext("three");
subject.onNext("four");
subject.onCompleted();
Observable.just("one", "two", "three", "four")
.repeat(3)
.subscribe(s -> System.out.println("observer emitted %s", s));
输出:
subject emitted one
subject emitted two
subject emitted three
subject emitted four
observer emitted one
observer emitted two
observer emitted three
observer emitted four
observer emitted one
observer emitted two
observer emitted three
observer emitted four
observer emitted one
observer emitted two
observer emitted three
observer emitted four
为什么主题上会忽略.repeat(3)?
谢谢!
答案 0 :(得分:3)
在第一个<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul class="testList">
<li class="a">should be grouped in a UL with id name = a</li>
<li class="b">2</li>
<li class="c">should be grouped in a UL with id name = c</li>
<li class="c">should be grouped in a UL with id name = c</li>
<li class="d">2</li>
<li class="e">3</li>
<li class="a">should be grouped in a UL with id name = a</li>
</ul>
之后,subscribe
在收到repeat
之前不会订阅PublicSubject
。您可以使用onCompleted
和doOnSubscribe
进行调试。如
doOnCompleted
这是执行顺序:
PublishSubject<String> subject = PublishSubject.create();
subject.doOnSubscribe(() -> System.out.println("subject subscribe"))
.doOnCompleted(() -> System.out.println("subject onCompleted"))
.repeat(3)
.subscribe(s -> System.out.printf("subject emitted %s\n", s));
subject.onNext("one");
subject.onNext("two");
subject.onNext("three");
subject.onNext("four");
subject.onCompleted();
实际上,如果要输出所有项目3次,可以使用subscribe to PublicSubject
subject.onNext("one") => output "one"
subject.onNext("two") => output "two"
subject.onNext("three") => output "three"
subject.onNext("four") => output "four"
subject.onCompleted() =>
output "onCompleted"
subscribe to PublicSubject // a new Observer is added to PublicSubject and PublicSubject is still emitting `onCompleted`,
// so this new Observer will receive `onCompleted` at once
output "onCompleted"
subscribe to PublicSubject // a new Observer is added to PublicSubject and PublicSubject is still emitting `onCompleted`,
// so this new Observer will receive `onCompleted` at once
output "onCompleted"
。
答案 1 :(得分:-1)
也许您可以像这样使用.asObservable()
:
subject.asObservable().repeat(3)
.subscribe(s -> System.out.println("subject emitted %s", s));