0

I'm initializing a long process on a request on the controller. I want to create a request object with Id, Status and other data and send it as a response to the client, so client doesn't wait for the whole process. It is like

private Mono<ProcessRequest> initializeProcess(List<String> params) {
    return Mono.just(new ProcessRequest(params)) // this is what I want to return
        .flapMap(request -> {
            // this is what I want to do after returning mono of request to the client
        }) 
}

Is it possible to do it like this way or the only option is to use some messaging like Kafka to perform computations after returning the response to the client?

Ruslan
  • 177
  • 1
  • 11

1 Answers1

2

What you want to achieve is some background operation that you want to execute on another thread. So, it is possible with subscribeOn() and calling subscribe() at your background operation (which is supposed to be any Publisher).

Then your background operation will be executed on a thread from Scheduler you provided to suscribeOn() and you will return immediately after calling subscribe() on that publisher.

private Mono<ProcessRequest> initializeProcess(List<String> params) {
    return Mono.just(new ProcessRequest(params))
            .doOnNext(processRequest ->
                    backgroundOperation() // Publisher - Mono or Flux
                            .subscribeOn(Schedulers.boundedElastic())
                            .subscribe()
            );
}
kerbermeister
  • 2,985
  • 3
  • 11
  • 30
  • Wouldn't it be sufficient to just use `backgroundOperation().subscribe()` when the boackgroundOperation itself is a publisher and is non-blocking? – Paul7979 Feb 24 '23 at 08:48
  • @Paul7979 if the backgroung operation does not switch the executing thread, then that background operation would be executed on the calling thread. Then you won't return immediately. – kerbermeister Feb 24 '23 at 08:50
  • Isn't the executing thread the reactor event loop? From my understanding it should not be necessary to switch threads as the event loop as long as the thread is not blocked by backgroundOperation – Paul7979 Feb 24 '23 at 09:05
  • @Paul7979 we don't know what is happening in backgroundOperation(), the author hasn't provided such details. Maybe there's no any IO call or something, when the executing will be switched to another thread. Then that operation will be executed on the caller thread, on the thread that called subscribe(). The similar problem I described here: https://stackoverflow.com/questions/57566465/fire-and-forget-with-reactor/75301517#75301517 – kerbermeister Feb 24 '23 at 11:20