Search code examples
androidrx-javaobservableobserver-patternrx-android

Create an observable emitter on android


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


Solution

  • 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.