2

I'm new to reactive programming and I'm using reactor through micronaut framework and kotlin. I'm trying to understand the advantages of reactive programming and how we implement it using Map and FlatMap through Mono and Flux.

I understand the non-blocking aspect of reactive programming but I'm confused if the operation on the data stream is actually asynchronous.

I've been reading about FlatMap and understand that they asynchronously produce inner streams and then merge these streams to another Flux without maintaining the order. The many diagrams I've seen all make it easier to understand but I have some basic questions when it comes down to actual use-cases.

Example:

fun updateDetials() {
        itemDetailsCrudRepository.getItems()
            .flatMap { 
                customerRepository.save(someTransferObject.toEntity(it))
            }
    }

In the above example assume itemDetailsCrudRepository.getItems() returns a Flux of a particular Entity. The flatMap operation has to save each of the items in the flux to another table. customerRepository.save() will save the item from the flux and we get the required entity through an instance of a data class someTransferObject.

Now, let's say the getItems() query returned 10 items and we need to save 10 rows in the new table. Is the flatMap operation(the operation of saving these items into the new table) applied to each item of the flux one at a time(synchronously) or does all the save happen at once asynchronously?

One thing I read was if subscribeOn(Scheduler.parallel()) is not applied then the flatMap operation is applied to each item in the flux one at a time(synchronously). Is this information right?

Please do correct me if my basic knowledge itself is incorrect.

Aditya
  • 33
  • 6
  • 1
    assuming the repositories are proper reactive nonblocking repositories, it will be concurrent, by default at most 256 items processed concurrently – Martin Tarjányi Feb 14 '23 at 21:08
  • also, if the publishers are producing the results in the same thread you can use `subscribeOn` inside the `flatMap` to make sure it's parallel – Igor Artamonov Apr 23 '23 at 17:40

1 Answers1

0

I think the asynchronous of flatMap is for next operator, cause it not in the order for next operator. For your example, if you want async save(), you can use

            .parallel(10)
            .runOn(Schedulers.parallel())

before flatMap and

            .sequential()

after flatMap.

superj
  • 1