Toffee Lu
Toffee Lu

Reputation: 123

How can I run some code async without blocking current coroutinescope in spring webflux kotlin coroutine just like subscribe()?

To create a background task without blocking current request "thread", I know I could use subscribe() in Spring WebFlux. But how can I do that in spring webflux kotlin coroutine? only GlobalScope.lanuch{} ?

Upvotes: 1

Views: 748

Answers (1)

Roman  Elizarov
Roman Elizarov

Reputation: 28658

The coroutine equivalents:

  • someFlux().subscribe { ... } becomes someFlow().onEach { ... }.launchIn(GlobalScope)
  • someMono().subscribe { ... } becomes GlobalScope.launch { someSuspendingFun() }

Both Reactor and Coroutine code shown above has the same problem that the background computation that was launched by the code works completely independently of the request that initiated it, so if requests come in a quick succession, then an application can quickly run out of resources. That is why is not recommended to do that in real production applications. However, it can be useful for one-time or periodic tasks or in the presence of other code that somehow puts a limit on the number of such independent background tasks.

Upvotes: 3

Related Questions