Search code examples
observablerx-java2

Why observable behavior eager when returning it from a rest endpoint?


@GetMapping(value = "/list", produces = "application/json; charset=utf-8")
public Observable<List<Person>> allPerson(){
        return Observable
                .range(0, Integer.MAX_VALUE)
                .map(this::listAllPerson)
                .takeWhile(list -> !list.isEmpty());
    }

The Observables are lazy but when returning an observable from a rest endpoint, for example, in a spring-boot app it behavior eager even without any subscription.

How and why?

This question may look stupid but I don't know and wondering answer.


Solution

  • There is a subscription under the hood. The framework (I guess you are using WebFlux) calls the allPerson() method when it receives a request, subscribes to the returned Observable and sends the content back to the caller. It all happens asynchronously, so the framework is able to handle multiple requests concurrently.