I have started learning about RxJava and RxAndroid. I would like to replace my observer pattern with RxJava. The observer pattern is similar to Android LocationManager class that has register and unregister methods. The "observable" class (not meaning rx.Observable) works in its own thread (HandlerThread) and owns map of listener and its Handler object and each of listener is called in its thread (via Handler). It's clear I think. So the question is how to implement it using RxJava? Does it make sense? I have read about PublishSubject and Subscriber but I don't know how to run my Observable in its thread. I don't want to use "subscribeOn" method because Subscriber doesn't create Observable but only subscribes to receiving notifications in its own thread. Thanks for any suggestions.
Asked
Active
Viewed 1,504 times
0
-
Hi, RxJava implements the observer-pattern for you. You just create streams of data and then subscribe. You may compose different observerables through operators. RxJava is not baised about threading. In fact RxJava is single threaded by default. Please have a look at this book "Reactive Programming with RxJava" (http://shop.oreilly.com/product/0636920042228.do). It will walk you through every nounce of RxJava with Android examples. – Sergej Isbrecht Nov 01 '16 at 21:18
1 Answers
2
Your general approach is a good one. Let me flesh out a few aspects for you.
Let's assume that your observable class is responsible for a value that changes over time. Previously, you would register an observer and the observable object would alert each observer when its value changed. Let's say you are watching color changes. (Warning: Untested code follows. I have used similar code for adapting Observer pattern into RxJava.)
PublishSubject<Color> ps1 = new PublishSubject<>(); // your observable class
Observable<Color> observable = ps1.observeOn(Schedulers.newThread());
...
// handler in another thread
Subscription sub = observable.subscribeOn(myThreadScheduler).subscribe(myHandler);
Now, your handler will be invoked on the thread specified by myThreadScheduler
. You can also cancel your observations by sub.unsubscribe()
.

Bob Dalgleish
- 8,167
- 4
- 32
- 42
-
Ok, but what about multiple observers? My Observable is a singleton, so there is only one worker thread. I suppose observers should not call subscribeOn method. I'm right? – piotrpawlowski Nov 04 '16 at 22:05
-
Each observer will execute that last line. What `subscribeOn()` does is perform the transfer of data between threads. – Bob Dalgleish Nov 07 '16 at 13:09