Search code examples
rx-javareactive-programming

How API with rxJava works


I have often seen API written in reactive way using rxJava. I have learnt the basic of rxJava and once thought I know how it works. But when I think about it again in the context of API, I start to not understand it. Why the API can work and return the response when there is no observer subscribing to the observable?

In rxJava, it is often explained with the use of observable and observer, and there is a subscribe action, e.g.

Observable<String> source = source.just("a", "b");
source.subscribe(s -> System.out.println(s));

But in API written using rxJava and using Spring, there is no observer and no subscribe action, e.g. a controller class as follow

@GetMapping(value = "/test")
public Observable<ServiceResponse> getTestValue(@RequestParam(value = "id") final String id) {
  return testService.getValue(id);
}

The "testService" class will do some processing such as calling another API to get some data, and do filtering, or mapping, etc. and it returns an observable.

But in the whole API, there is no subscribe action and no observer. Yet, why it is able to return a response ?


Solution

  • The client of the API the observer, and they are expected to do the subscribe. So, in your example, it's expected that the client will do this:

    getTestValue("someId")
       /* maybe some other operators here */
       .subscribe();
    

    That "client" could an developer who is using your API to develop their own application, or it could be the internals of some framework that you're integrating with (which is likely the case in your example, given the use of annotations).