How can I implement scenario when I want to add elements after creation of the Observable, can it be done at all? In the Observer pattern I would just fire event or so. Do you have some ideas?
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
RxJava provides many methods in its library to create an Observable. Choosing which one to use can be difficult. My goal from this article is to help you in making this choice simpler by providing you with a mental map of different scenarios and which methods to use in each scenario.
onNext(): This method is called when a new item is emitted from the Observable. onError(): This method is called when an error occurs and the emission of data is not successfully completed. onComplete(): This method is called when the Observable has successfully completed emitting all items.
An Observable is like a speaker that emits a value. It does some work and emits some values. An Operator is like a translator which translates/modifies data from one form to another form. An Observer gets those values.
You can't - not to the observable you created. What you need is a Subject
, using which you can emit values.
Subject
is basically both an Observable
and an Observer
.
For example:
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With