简体   繁体   中英

When to use .flatMap() on a Mono instead of just calling a function on a value?

I'm looking at some code where .flatMap was called on a Mono - I've gone through some of the PR discussions on Rx GitHubs about adding such functionality, but I don't really understand why someone would do that: flatMap, to me, seems inherently purposed for applying a function to 1...n elements. Applying a function to 0...1 elements can be done with a single function call.

You can use .map() as long as it is non-blocking.

Otherwise, your inner transformation will return Mono that will complete in future (eg a network call), and you should subscribe on it with .flatMap instead of blocking the processing.

flatMap works with any Publisher<T> and works with any 0..n where n can also be 0 .

If you need to transform one element into a few (eg split a String) then you can use flatMapIterable , it has lower overhead than flatMap .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM