Adam Hughes
Adam Hughes

Reputation: 16309

How to dynamically update an RX Observable?

(Working in RxKotlin and RxJava, but using metacode for simplicity)

Many Reactive Extensions guides begin by creating an Observable from already available data. From The introduction to Reactive Programming you've been missing, it's created from a single string

var soureStream= Rx.Observable.just('https://api.github.com/users');

Similarly, from the frontpage of RxKotlin, from a populated list

val list = listOf(1,2,3,4,5)
list.toObservable()     

Now consider a simple filter that yields an outStream,

var outStream = sourceStream.filter({x > 3})

In both guides the source events are declared apriori. Which means the timeline of events has some form

source: ----1,2,3,4,5-------
out:    --------------4,5---

How can I modify sourceStream to become more of a pipeline? In other words, no input data is available during sourceStream creation? When a source event becomes available, it is immediately processed by out:

source: ---1--2--3-4---5-------
out:    ------------4---5-------

I expected to find an Observable.add() for dynamic updates

var sourceStream = Observable.empty()
var outStream = sourceStream.filter({x>3})

//print each element as its added 
sourceStream .subscribe({println(it)})
outStream.subscribe({println(it)})

for i in range(5):
    sourceStream.add(i)

Is this possible?

Upvotes: 3

Views: 1508

Answers (1)

Daniel T.
Daniel T.

Reputation: 33967

I'm new, but how could I solve my problem without a subject? If I'm testing an application, and I want it to "pop" an update every 5 seconds, how else can I do it other than this Publish subscribe business? Can someone post an answer to this question that doesn't involve a Subscriber?

If you want to pop an update every five seconds, then create an Observable with the interval operator, don't use a Subject. There are some dozen different operators for constructing Observables so you rarely need a subject.

That said, sometimes you do need one, and they come in very handy when testing code. I use them extensively in unit tests.

To Use Subject Or Not To Use Subject? is and excellent article on the subject of Subjects.

Upvotes: 3

Related Questions