Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add elements after creation of rx Observable

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
like image 981
Eddie Jamsession Avatar asked Nov 26 '13 23:11

Eddie Jamsession


People also ask

Can we create our own Observable in RxJava?

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.

What is onNext in RxJava?

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.

What is RX Observable in Java?

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.


1 Answers

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'   
like image 66
PeterParameter Avatar answered Oct 31 '22 19:10

PeterParameter