0

比方說,我有以下代碼:FlatMap和主題 - 如何避免重複訂閱者?

BehaviorSubject<Integer> subject = BehaviorSubject.create(); 
BehaviorSubject<Integer> subject2 = BehaviorSubject.create(); 
subject. 
     doOnNext(number -> subject2.onNext(number)). 
     flatMap(number -> subject2). 
     subscribe(number -> System.out.println("Number " + number)); 

for(int i = 0; i < 10; i++) { 
    subject.onNext(i); 
} 

它產生的輸出是:

Number 0 
Number 1 
Number 1 
Number 2 
Number 2 
Number 2 
Number 3 
Number 3 
Number 3 
Number 3 
Number 4 
Number 4 
Number 4 
Number 4 
Number 4 

和和。

我明白爲什麼會發生這種情況 - 這是因爲每次調用flatMap時,都會將新用戶添加到subject2

問題是 - 如何避免這種情況?

回答

1

可以限制subject2一個元素中flatMap這樣的:

flatMap(number -> subject2.first())

代碼

BehaviorSubject<Integer> subject = BehaviorSubject.create(); 
    BehaviorSubject<Integer> subject2 = BehaviorSubject.create(); 
    subject. 
      doOnNext(number -> subject2.onNext(number)). 
      flatMap(number -> subject2.first()). 
      subscribe(number -> System.out.println("Number " + number)); 

    for(int i = 0; i < 10; i++) { 
     subject.onNext(i); 
    } 

產生不包含重複