Reactor – Simple Ways to create Flux/Mono

Reactive Streams is an API and pattern that provides a standard for asynchronous stream processing with non-blocking back pressure. It is also being introduced in Java 9 Flow API with four simple interfaces: Publisher, Subscriber, Subscription and Processor.

But Reactive Streams API is just low level to make practical use in reactive applications. So Reactor Core provides two main implementations of Publisher: Flux and Mono. In this tutorial, we’re gonna know what they are and simple ways to create them.

I. Overview

For more details about Reactive Streams and Publish-Subscribe Pattern, please visit:
Java 9 Flow API – Reactive Streams

1. Flux & Mono

A Flux<T> is a standard Publisher<T> representing a reactive sequence of 0..N items, optionally terminated by either a success signal or an error.

While Mono<T> is a specialized Publisher<T> that emits at most single-valued-or-empty result.

2. Simple ways to create Publishers with Flux and Mono

2.1 Mono

Empty Mono:

Mono<String> noData = Mono.empty();

– Mono with value:

Mono<String> data = Mono.just("JSA");

– Mono that emits an Exception:


Mono.error(new CustomException());

2.2 Flux

Empty Flux:

Flux<String> noData = Flux.empty();

– Flux with items:

Flux<String> data = Flux.just("Java", "Sample", "Approach", ".com");

– Flux from Collections:

List<String> list = Arrays.asList("JAVA", "SAMPLE", "APPROACH", ".COM");
Flux<String> sequence = Flux.fromIterable(list);

– Flux that is infinite and ticks every x units of time with an increasing Long:

Flux<Long> counter = Flux.interval(Duration.ofMillis(x));

– Flux that emits an Exception:


Flux.error(new CustomException());

II. Practice

0. Technology

– Java 8
– Maven 3.6.1
– Reactor Core 3.0.4, with the Aluminium release train.

1. Reactor installation in Maven

– First, import the BOM by adding the following to pom.xml:

<dependencyManagement>
	<dependencies>
		<dependency>
			<groupId>io.projectreactor</groupId>
			<artifactId>reactor-bom</artifactId>
			<version>Aluminium-SR1</version>
			<type>pom</type>
			<scope>import</scope>
		</dependency>
	</dependencies>
</dependencyManagement>
</pre>
- Next, add dependency:
<pre class="lang:xml">
<dependencies>
	<dependency>
		<groupId>io.projectreactor</groupId>
		<artifactId>reactor-core</artifactId>
	</dependency>
</dependencies>

2. Write Code

package com.javasampleapproach.reactorpublisher;

import java.time.Duration;
import java.util.Arrays;
import java.util.List;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

public class MainApp {

	public static void main(String[] args) throws InterruptedException {

		System.out.println("=== Empty Mono ===");
		Mono.empty().subscribe(System.out::println);

		System.out.println("=== Mono.just ===");
		Mono.just("JSA")
			.map(item -> "Mono item: " + item)
			.subscribe(System.out::println);
		
		System.out.println("=== Empty Flux ===");
		Flux.empty()
			.subscribe(System.out::println);

		System.out.println("=== Flux.just ===");
		Flux.just("Java", "Sample", "Approach", ".com")
			.map(item -> item.toUpperCase())
			.subscribe(System.out::print);

		System.out.println("\n=== Flux from List ===");
		List<String> list = Arrays.asList("JAVA", "SAMPLE", "APPROACH", ".COM");
		Flux.fromIterable(list)
			.map(item -> item.toLowerCase())
			.subscribe(System.out::print);

		System.out.println("\n=== Flux emits increasing values each 100ms ===");
		Flux.interval(Duration.ofMillis(100))
			.map(item -> "tick: " + item)
			.take(10)
			.subscribe(System.out::println);
		
		Thread.sleep(1500);

		System.out.println("=== Mono emits an Exception ===");
		Mono.error(new CustomException("Mono"))
			.doOnError(e -> {System.out.println("inside Mono doOnError()");})
			.subscribe(System.out::println);
		
		System.out.println("=== Flux emits an Exception ===");
		Flux.error(new CustomException("Flux"))
			.subscribe(System.out::println);
	}
}
package com.javasampleapproach.reactorpublisher;

public class CustomException extends RuntimeException {

	private static final long serialVersionUID = -5970845585469454688L;

	public CustomException(String type) {
		System.out.println(type + ": throw CustomException!");
	}
}

3. Run & Check Result


=== Empty Mono ===
=== Mono.just ===
Mono item: JSA
=== Empty Flux ===
=== Flux.just ===
ozenero.com
=== Flux from List ===
ozenero.com
=== Flux emits increasing values each 100ms ===
tick: 0
tick: 1
tick: 2
tick: 3
tick: 4
tick: 5
tick: 6
tick: 7
tick: 8
tick: 9
=== Mono emits an Exception ===
Mono: throw CustomException!
inside Mono doOnError()
=== Flux emits an Exception ===
Flux: throw CustomException!
Exception in thread "main" reactor.core.Exceptions$ErrorCallbackNotImplemented: com.javasampleapproach.reactorpublisher.CustomException
Caused by: com.javasampleapproach.reactorpublisher.CustomException
	at com.javasampleapproach.reactorpublisher.MainApp.main(MainApp.java:50)

214 thoughts on “Reactor – Simple Ways to create Flux/Mono”

  1. i have visited this blog a couple of times now and i have to tell you that i find it quite nice actually. continue doing what youre doing! :p

  2. Wonderful learn, I simply handed this onto a colleague who was doing some research on that. And he actually purchased me lunch because I discovered it for him smile So let me rephrase that: Thanks for lunch! Anyway, in my language, there should not much good source like this.

  3. Thanks for your submission. I would love to remark that the very first thing you will need to conduct is to see if you really need credit restoration. To do that you will need to get your hands on a duplicate of your credit history. That should never be difficult, since government makes it necessary that you are allowed to receive one absolutely free copy of the credit report each year. You just have to request that from the right persons. You can either check out the website for that Federal Trade Commission or contact one of the leading credit agencies immediately.

  4. Hi! Do you know if they make any plugins to assist with SEO? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good results. If you know of any please share. Cheers!

  5. I haven抰 checked in here for a while since I thought it was getting boring, but the last few posts are great quality so I guess I will add you back to my daily bloglist. You deserve it my friend 🙂

  6. Hi, Neat post. There’s a problem with your site in internet explorer, would test this?IE still is the market leader and a huge portion of people will miss your fantastic writing because of this problem.

  7. 722440 317421Chaga mushroom tea leaf is thought-about any adverse health elixir at Spain, Siberia and lots of n . Countries in europe sadly contains before you go ahead significantly avoidable the main limelight under western culture. Mushroom 93688

  8. With almost everything that appears to be building throughout this area, a significant percentage of perspectives are relatively radical. Nonetheless, I appologize, but I do not give credence to your whole strategy, all be it stimulating none the less. It seems to me that your opinions are not completely validated and in reality you are yourself not thoroughly convinced of the assertion. In any event I did appreciate reading through it.

  9. I wanted to put you that little bit of remark to be able to give many thanks once again just for the extraordinary secrets you have contributed in this article. It’s simply incredibly open-handed with you to deliver without restraint all that most people might have sold for an electronic book to earn some money for themselves, particularly considering the fact that you might have tried it in case you wanted. Those points as well acted as a great way to understand that someone else have the same desire similar to my very own to know the truth whole lot more with regards to this problem. I am sure there are lots of more enjoyable moments ahead for people who look into your website.

  10. I’m not that much of a online reader to be honest but your sites
    really nice, keep it up! I’ll go ahead and bookmark your website to come
    back in the future. Many thanks

  11. Nice weblog here! Also your website quite a bit up
    very fast! What web host are you the usage of?
    Can I am getting your affiliate link in your host? I wish my site loaded
    up as fast as yours lol

  12. Nice post. I was checking constantly this weblog and I’m inspired!
    Very helpful info specially the ultimate phase 🙂 I maintain such info a lot.
    I used to be seeking this particular info for a very lengthy time.
    Thank you and good luck.

  13. I do accept as true with all of the ideas you’ve introduced in your post.
    They’re very convincing and can definitely work. Still, the posts are too quick
    for newbies. May just you please extend them a
    bit from next time? Thanks for the post.

  14. I’ve been browsing online more than three hours today, but
    I never discovered any fascinating article like yours.
    It’s lovely value sufficient for me. In my opinion, if all site
    owners and bloggers made just right content as you did, the
    web might be much more useful than ever before.

  15. Hi, Neat post. There is a problem with your web site in internet explorer, would check
    this? IE nonetheless is the market chief and a large portion of other people
    will miss your great writing because of this problem.

  16. Attractive section of content. I just stumbled upon your web site and in accession capital to
    assert that I acquire actually enjoyed account your blog posts.
    Any way I will be subscribing to your feeds and even I achievement
    you access consistently rapidly.

  17. whoah this weblog is magnificent i like studying your articles.
    Keep up the great work! You understand, a
    lot of persons are searching round for this information, you could aid them greatly.

  18. Definitely consider that that you stated. Your favorite reason seemed to be on the net the simplest
    thing to be aware of. I say to you, I certainly get irked even as people think about worries that they
    plainly don’t understand about. You managed to hit the nail upon the highest as smartly as outlined out
    the entire thing with no need side-effects
    , people can take a signal. Will probably be again to get more.
    Thanks

  19. It’s a shame you don’t have a donate button! I’d without a doubt donate
    to this outstanding blog! I guess for now i’ll settle for bookmarking and adding your RSS feed
    to my Google account. I look forward to new updates and will share this site with
    my Facebook group. Talk soon!

  20. I know this if off topic but I’m looking into starting my own blog and was wondering what all is needed to get setup?

    I’m assuming having a blog like yours would cost a pretty penny?
    I’m not very internet smart so I’m not 100% positive.

    Any suggestions or advice would be greatly appreciated.
    Many thanks

  21. Magnificent items from you, man. I’ve remember your stuff prior to and you are just too
    wonderful. I actually like what you have got here, really like what you
    are stating and the way in which through which
    you say it. You make it enjoyable and you continue to take care of to stay it smart.

    I can not wait to learn far more from you. That is actually a tremendous website.

  22. Hi would you mind letting me know which hosting company you’re utilizing?
    I’ve loaded your blog in 3 completely different web browsers
    and I must say this blog loads a lot faster then most.
    Can you suggest a good hosting provider at a honest price?
    Thanks a lot, I appreciate it!

  23. I simply could not depart your website prior to suggesting that I extremely enjoyed the standard information an individual supply for your visitors?
    Is going to be back often to investigate cross-check new posts

  24. whoah this weblog is fantastic i really like studying
    your articles. Stay up the great work! You understand, many individuals are looking around for this info, you can aid them greatly.

  25. I’m curious to find out what blog system you happen to
    be utilizing? I’m having some small security issues with my
    latest website and I’d like to find something more secure.

    Do you have any recommendations?

  26. Have you ever considered about adding a little bit more than just your
    articles? I mean, what you say is fundamental and everything.

    Nevertheless imagine if you added some great graphics or
    videos to give your posts more, “pop”! Your content is excellent but with
    images and videos, this site could undeniably be one of the most beneficial in its field.
    Wonderful blog!

  27. Hi! I know this is kind of off topic but I was wondering if you
    knew where I could locate a captcha plugin for my comment form?
    I’m using the same blog platform as yours and I’m having trouble finding one?
    Thanks a lot!

  28. We stumbled over here by a different website and thought I might
    as well check things out. I like what I see so i am just following you.

    Look forward to exploring your web page again.

  29. Awesome blog! Is your theme custom made or did you download it from somewhere?
    A design like yours with a few simple adjustements would really make my blog stand out.
    Please let me know where you got your theme. Cheers

  30. I don’t know if it’s just me or if everybody else encountering issues with your
    blog. It appears as though some of the text in your posts are running off the screen. Can someone
    else please provide feedback and let me know if this is happening to them as well?
    This might be a issue with my web browser because I’ve had this happen previously.
    Thanks

  31. Every weekend i used to visit this web page, because i want enjoyment, since this this web site conations actually good funny stuff too.

  32. Greetings! Very useful advice in this particular article!
    It’s the little changes that make the most important changes.
    Thanks a lot for sharing!

  33. I’m no longer certain where you’re getting your info, however good topic.
    I must spend some time finding out more or working
    out more. Thank you for fantastic info I used to be on the
    lookout for this info for my mission.

  34. You actually make it seem so easy with your presentation but I find this matter to be really
    something which I think I would never understand.
    It seems too complicated and very broad for me. I am looking forward for your next post, I will try to get the hang of it!

  35. It’s appropriate time to make some plans for the long run and it is time to
    be happy. I have read this publish and if I may just I wish to recommend you few interesting issues or suggestions.
    Maybe you can write next articles relating to this article.
    I want to learn more things about it!

  36. Greetings! I know this is kinda off topic but I was wondering which blog
    platform are you using for this website? I’m getting fed up of WordPress because I’ve had issues with hackers
    and I’m looking at alternatives for another platform.

    I would be great if you could point me in the direction of a good platform.

  37. Excellent blog right here! Also your website a lot up very fast!
    What web host are you the use of? Can I am getting your associate link for your host?
    I want my web site loaded up as fast as yours lol

  38. Howdy, i read your blog from time to time and i own a similar one and i was just wondering
    if you get a lot of spam responses? If so how do you prevent it, any plugin or anything you can suggest?
    I get so much lately it’s driving me crazy so
    any support is very much appreciated.

  39. I would like to thank you for the efforts you’ve put in writing this site.
    I am hoping to view the same high-grade blog posts from
    you in the future as well. In truth, your creative writing abilities has encouraged
    me to get my own, personal website now 😉

  40. When I initially left a comment I seem to have clicked the -Notify
    me when new comments are added- checkbox and from now on each time a comment is added I get
    four emails with the same comment. Perhaps there is a means you are able to remove me
    from that service? Cheers!

  41. Excellent beat ! I would like to apprentice while you amend your website, how can i subscribe for a blog web site?
    The account helped me a acceptable deal. I had been a little bit acquainted of this your broadcast offered bright clear idea

  42. I am really inspired along with your writing abilities
    and also with the format for your blog. Is that
    this a paid subject matter or did you customize it yourself?
    Anyway keep up the excellent high quality writing, it’s rare to look a great blog like this one today..

  43. Wonderful blog! Do you have any hints for aspiring writers?
    I’m planning to start my own website soon but I’m a little
    lost on everything. Would you propose starting with a free platform like WordPress or go for a paid option? There are
    so many choices out there that I’m totally confused
    .. Any recommendations? Cheers!

  44. Hmm is anyone else encountering problems with the images on this
    blog loading? I’m trying to find out if its a problem
    on my end or if it’s the blog. Any feed-back would be greatly
    appreciated.

  45. I don’t even know the way I ended up here, but I believed this submit used to be great.
    I don’t understand who you are but certainly you’re
    going to a well-known blogger in the event you are not already.
    Cheers!

  46. Excellent beat ! I would like to apprentice while you amend your web site, how can i subscribe for a blog web site?
    The account aided me a acceptable deal. I had been a little bit acquainted of this your broadcast offered bright clear
    idea

  47. Greetings, There’s no doubt that your site
    may be having web browser compatibility problems. When I take a look at your web site in Safari, it looks fine however, if opening in I.E., it has some overlapping issues.
    I simply wanted to give you a quick heads up! Besides that, excellent blog!

  48. You’ve made some really good points there. I checked on the net for more info about the issue
    and found most people will go along with your views on this website.

  49. Howdy! This is kind of off topic but I need some help from an established blog.
    Is it hard to set up your own blog? I’m not very techincal but I can figure things out pretty fast.
    I’m thinking about creating my own but I’m not sure
    where to begin. Do you have any ideas or suggestions?
    Thanks

  50. I’m not sure why but this blog is loading extremely slow
    for me. Is anyone else having this problem or is it a issue on my end?

    I’ll check back later on and see if the problem still
    exists.

  51. My partner and I absolutely love your blog and find nearly all
    of your post’s to be precisely what I’m looking for. Does one
    offer guest writers to write content for yourself?

    I wouldn’t mind writing a post or elaborating on most of the subjects you write regarding here.
    Again, awesome website!

  52. When someone writes an article he/she maintains the image of a user
    in his/her mind that how a user can know it. So that’s why this article is amazing.

    Thanks!

  53. Howdy outstanding blog! Does running a blog such as this take a large amount of work?

    I have virtually no expertise in coding but I had been hoping to start my
    own blog soon. Anyhow, if you have any ideas or tips
    for new blog owners please share. I know this is off topic however I
    simply had to ask. Kudos!

  54. Thanks for every other informative web site. Where else may I get that type of information written in such a perfect way?
    I have a mission that I’m simply now running on, and I’ve been at the
    look out for such info.

  55. Hmm is anyone else having problems with the images on this blog loading?
    I’m trying to figure out if its a problem on my end or if it’s
    the blog. Any responses would be greatly appreciated.

  56. Hi, I do think your site might be having internet browser
    compatibility issues. Whenever I look at your web site in Safari,
    it looks fine but when opening in IE, it has some overlapping issues.
    I merely wanted to give you a quick heads up!
    Besides that, great site!

  57. Hello! This post couldn’t be written any better! Reading through this post reminds me of my old room
    mate! He always kept chatting about this. I will forward this page to him.
    Fairly certain he will have a good read. Thank you for sharing!

  58. Great blog here! Additionally your website lots up very fast!

    What web host are you the usage of? Can I am getting your affiliate link to your host?
    I wish my web site loaded up as fast as yours lol

  59. Great items from you, man. I have understand your stuff prior to and you’re just extremely fantastic.
    I really like what you have obtained here, certainly like what you are stating and the way in which
    during which you are saying it. You make it entertaining and you still care for to keep it
    wise. I cant wait to read much more from you. That is actually a tremendous web site.

  60. What i do not understood is actually how you are now not
    actually a lot more well-preferred than you might be now.
    You’re very intelligent. You already know thus considerably in terms of this
    subject, made me individually consider it from numerous numerous angles.
    Its like men and women are not involved until it is one thing to do with Lady gaga!

    Your own stuffs excellent. Always deal with it up!

  61. Just desire to say your article is as amazing.
    The clarity on your put up is simply excellent and i can assume you’re an expert
    in this subject. Fine along with your permission let me to seize your feed
    to keep up to date with coming near near post. Thank you one million and please carry on the gratifying work.

  62. Hi, I do think this is an excellent site. I stumbledupon it 😉 I
    will revisit yet again since i have book marked it. Money and freedom is the greatest way to change, may you
    be rich and continue to guide other people.

  63. Simply wish to say your article is as amazing. The clearness in your post is just cool and
    i could assume you’re an expert on this subject. Fine with your permission let me to grab your feed to keep updated with forthcoming post.
    Thanks a million and please continue the enjoyable work.

  64. I do not know whether it’s just me or if perhaps
    everyone else experiencing problems with your site.
    It appears like some of the written text on your posts
    are running off the screen. Can somebody else please
    provide feedback and let me know if this is happening to them as well?
    This may be a issue with my browser because I’ve had this happen previously.
    Many thanks

  65. Hey I know this is off topic but I was wondering if you knew of
    any widgets I could add to my blog that automatically tweet my newest
    twitter updates. I’ve been looking for a plug-in like this for quite some time and was hoping maybe
    you would have some experience with something like this.
    Please let me know if you run into anything.
    I truly enjoy reading your blog and I look forward to your new updates.

  66. Does your site have a contact page? I’m having problems locating it but, I’d like to
    shoot you an e-mail. I’ve got some creative ideas for your blog you
    might be interested in hearing. Either way, great website and I look forward to seeing it expand over time.

  67. I absolutely love your site.. Pleasant colors & theme.
    Did you develop this amazing site yourself? Please
    reply back as I’m wanting to create my very own blog and would love to find
    out where you got this from or exactly what the theme is named.
    Thanks!

  68. Hmm it looks like your blog ate my first comment
    (it was super long) so I guess I’ll just sum it up what I submitted
    and say, I’m thoroughly enjoying your blog. I as well am an aspiring blog blogger but I’m still
    new to the whole thing. Do you have any points for rookie blog writers?
    I’d certainly appreciate it.

  69. It is actually a nice and useful piece of information.
    I am satisfied that you simply shared this helpful
    info with us. Please stay us up to date like this.
    Thanks for sharing.

  70. An impressive share! I have just forwarded this onto a co-worker who was conducting a
    little homework on this. And he actually ordered me dinner because I stumbled upon it for him…
    lol. So let me reword this…. Thanks for the meal!!
    But yeah, thanks for spending the time to talk about this subject here
    on your blog.

  71. I do consider all of the concepts you’ve presented for your
    post. They are very convincing and will certainly
    work. Still, the posts are very brief for newbies. Could you please lengthen them a bit from next time?
    Thank you for the post.

  72. Just desire to say your article is as amazing. The clarity for your post is just excellent and i can think you’re an expert on this subject.
    Well with your permission let me to clutch your RSS feed to stay updated with impending post.
    Thanks 1,000,000 and please continue the enjoyable work.

  73. I believe everything said was actually very reasonable. But, what about this?
    suppose you wrote a catchier post title?
    I am not suggesting your information isn’t solid, but what if you added a title that grabbed people’s attention? I mean ozenero | Mobile & Web Programming
    Tutorials is a little vanilla. You should look at
    Yahoo’s front page and watch how they create news titles to grab viewers interested.

    You might try adding a video or a related picture or two to
    grab people excited about what you’ve got to say.
    Just my opinion, it could make your blog a little livelier.

  74. Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog
    that automatically tweet my newest twitter updates.

    I’ve been looking for a plug-in like this for quite some time
    and was hoping maybe you would have some experience with something like this.
    Please let me know if you run into anything. I truly enjoy reading your blog and I
    look forward to your new updates.

  75. My brother recommended I might like this blog.
    He was totally right. This post actually made my day.
    You can not imagine just how much time I had spent for this information! Thanks!

  76. Hello excellent website! Does running a blog similar to this take a massive amount work?
    I’ve absolutely no expertise in computer programming
    however I had been hoping to start my own blog in the near future.
    Anyhow, should you have any suggestions or tips for new blog
    owners please share. I understand this is off subject but I just had to ask.
    Kudos!

  77. Attractive section of content. I just stumbled upon your web site and in accession capital
    to assert that I get actually enjoyed account your
    blog posts. Any way I’ll be subscribing to your augment and even I achievement you access consistently rapidly.

  78. Hi! I know this is kind of off topic but I was wondering if you knew where I could get
    a captcha plugin for my comment form? I’m using the same blog
    platform as yours and I’m having difficulty finding one?

    Thanks a lot!

  79. Someone necessarily assist to make severely articles I might state.
    This is the first time I frequented your web page and to this point?
    I amazed with the research you made to create this particular submit amazing.
    Excellent job!

  80. 695180 972134Excellent paintings! This is the kind of information that really should be shared around the web. Disgrace on Google for now not positioning this publish upper! Come on more than and speak over with my website . Thanks =) 196586

  81. I like what you guys are up too. Such smart work and reporting! Carry on the excellent works guys I’ve incorporated you guys to my blogroll. I think it will improve the value of my website 🙂

  82. Oh my goodness! Awesome article dude! Thank you so much, However I am going through problems
    with your RSS. I don’t know why I cannot join it. Is there anybody having identical RSS problems?
    Anybody who knows the solution will you kindly respond?

    Thanks!!

Leave a Reply

Your email address will not be published. Required fields are marked *