Reputation: 2295
I have an android application which receives data from a websocket connection. This data is stored on a Hashmap and must be recovered from some points of the application. I have created a "get" method that makes a Observable.just() with that data, however, I need another Observable.just() when the data is received from the websocket so the subscriber of the first observable can receive the updated data, how should I do that? Do I have to create an Observable object and always do the "just" to that observable? How must I emit the data in order to always be received for the same subscriber (the same way as realm does)?
Thanks in advance
Upvotes: 1
Views: 4554
Reputation: 13481
RxJava has Hot Observables, in your case you need to use subject, to pass the emission of one observable to another.
check this unit test
/**
* In this example we see how using hot observables ReplaySubject we can emit an item on broadcast to all the observers(subscribers).
*
* @throws InterruptedException
*/
@Test
public void testHotObservableUsingReplaySubject2() throws InterruptedException {
Observable<Long> interval = Observable.interval(100L, TimeUnit.MILLISECONDS);
Subject<Long, Long> publishSubject = ReplaySubject.create(1);
interval.subscribe(publishSubject);
Thread.sleep(1000L);
publishSubject.subscribe(System.out::println, (e) -> System.err.println(e.getMessage()), System.out::println);
}
You can see more examples of Hot Observables here https://github.com/politrons/reactive/blob/master/src/test/java/rx/observables/connectable/HotObservable.java
Upvotes: 2
Reputation: 157487
I need another Observable.just() when the data is received from the websocket so the subscriber of the first observable can receive the updated data, how should I do that?
Subject is what you probably you are looking for. Subject is an object that can act at the same time as Subscriber
and Observable
. If your get() returns Subject#asObservable
instead of Observable.just
, and every time you get fresh data from your websocket you call Subject#onNext
, you will get the desired behaviour. Subject
itself is abstract, but RxJava
provides some concrete implementations. Please refer to the documentation to understand the difference between them and choose the one that suits you better.
Upvotes: 2