I have been reading a little about rx-java recently. I am wondering whether the framework fits the bill for a communication system between threads. I am working on a REST server written in java. Each time some resource is PUT/POSTed I want to do some computation using a pool of worker threads. However, I would still like to be able to monitor the requests, maybe to print out some statistics. Essentially I would like an Observable
so I can deal with the requests in a flexible way with multiple Observer
s.
My question is, how can I create a suitable Observable
? Most guides I have seen deal with operations on Observables, such as mapping etc. Obervables are mostly created from collections or integer ranges. In any case it seems to be impossible to push new values to the created Observables. Apparently the only way to retain this flexibility is to use Observable.create
. However, this seems to be rather low-level. I would have to implement a list of queues for each new subscriber and do a synchronized
push to every single one. Is this really necessary or is something like this implemented already in rx-java?
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.
fromCallable example: Callable<String> callable = () -> { System. out. println("Hello World!"); return "Hello World!"); } Observable<String> observable = Observable. fromCallable(callable); observable.
There are two main methods to create Observables in RxJS. Subjects and Operators. We will take a look at both of these!
What you're looking for is a Subject. These act as both Observer and Observables. For example a ReplaySubject
will replay all events sent to it to all subscribers.
Subject<String> replaySubject = ReplaySubject.create();
replaySubject.subscribe(s -> System.out.println(s));
// elsewhere...
replaySubject.onNext("First");
replaySubject.onNext("Second");
replaySubject.onComplete();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With