2013-11-26 90 views
11

如何在創建Observable後添加元素時如何實現場景,完全可以實現?在觀察者模式中,我只會觸發事件。你有什麼想法嗎?創建rx後添加元素Observable

import rx.lang.scala._ 

val target = Observable(1,2,3,4) 

val subscription1 = target subscribe(println(_)) 
val subscription2 = target subscribe(println(_)) 


def addToObservable(toAdd: Int, target: Observable[Int]): Observable[Int] = { 
    target/*.addElementAndNotifyObservers(toAdd)*/ 
} 

addToObservable(4, target) //should print 4 on all subscriptions 
addToObservable(6, target) //should print 6 on all subscriptions 

回答

11

你不能 - 對你創建的觀察者不能。你需要的是一個Subject,你可以使用它發出值。基本上都是ObservableObserver

例如:

import rx.lang.scala._ 
import rx.lang.scala.subjects._ 

val subject = ReplaySubject[Int]()    
val initial = Observable(1,2,3,4)  
val target = initial ++ subject // concat the observables 

val subscription1 = target subscribe(println(_)) 
val subscription2 = target subscribe(println(_)) 

subject.onNext(4) // emit '4' 
subject.onNext(6) // emit '6'