Reactor – How to Create Flux (Publisher) with Interval

In this tutorial, JavaSampleApproach introduces simple ways to create Publisher (Flux) that emits items every specified Interval of time.

I. Overview

1. Steps to do

Our goal is to create Flux for (data1, data2, data3, …) that emits items every specified Interval of time.

– First, we need to produce a Flux<Long> that is infinite and emits regular ticks from a clock -> use Flux.interval(Duration).
Now we have Flux<Long>: (i1, i2, i3, …)

– Then we have several ways to convert each Long item (i) to each data item (data) that we want to publish:
+ transform i to data -> use map(i -> data).
+ zip i with data together -> use zipWith(publisher,combinator) or zipWithIterable(collection). Then separate Zip(i,data) to get data.

2. Methods’ details
1. Flux#interval

This method creates a new Flux that emits incrementing Long starting with 0 every period.

static Flux interval(Duration period);
2. Flux.zipWithIterable

Pairwise combines as Tuple2 elements of the Flux and an Iterable sequence.

Flux> zipWithIterable(Iterable iterable)

To get the content of Tuple2 in Type-safe way:

Tuple2 tuple2 = ...; // tuple2(object1,object2)

T object1 = tuple2.getT1();
T2 object2 = tuple2.getT2();
3. Flux.zipWith

The operator will forward all combinations produced by the combinator from the most recent items emitted by source<T> (that invokes zipWith() method) and source2<T2> (that contains data item to be zipped with source item):

final Flux zipWith(Publisher source2, final BiFunction combinator);

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:


	
		
			io.projectreactor
			reactor-bom
			Aluminium-SR1
			pom
			import
		
	

– Next, add dependency:


	
		io.projectreactor
		reactor-core
	

2. Code
2.1 Using map()
List data = new ArrayList(Arrays.asList("{A}", "{B}", "{C}"));
Flux intervalFlux1 = Flux
							.interval(Duration.ofMillis(500))
							.map(tick -> {
								if (tick < data.size())
									return "item " + tick + ": " + data.get(tick.intValue());
								return "Done (tick == data.size())";
							});

intervalFlux1.take(data.size() + 1).subscribe(System.out::println);
Thread.sleep(3000);

Result:

item 0: {A}
item 1: {B}
item 2: {C}
Done (tick == data.size())
2.2 Using zipWithIterable()
List data = new ArrayList(Arrays.asList("{A}", "{B}", "{C}"));
Flux intervalFlux2 = Flux
							.interval(Duration.ofMillis(500))
							.zipWithIterable(data)
							.map(source -> "item " + source.getT1() + ": " + source.getT2());

intervalFlux2.subscribe(System.out::println);
Thread.sleep(3000);

Result:

item 0: {A}
item 1: {B}
item 2: {C}
2.3 Using zipWith()
Flux flux = Flux.just("{A}", "{B}", "{C}");
Flux intervalFlux3 = Flux
							.interval(Duration.ofMillis(500))
							.zipWith(flux, (i, item) -> "item " + i + ": " + item);
		
intervalFlux3.subscribe(System.out::println);
Thread.sleep(3000);

Result:

item 0: {A}
item 1: {B}
item 2: {C}

III. Source Code

package com.javasampleapproach.reactor.publisherinterval;

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

import reactor.core.publisher.Flux;

public class MainApp {

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

		System.out.println("=== from Collection using map() ===");
		List data = new ArrayList(Arrays.asList("{A}", "{B}", "{C}"));
		Flux intervalFlux1 = Flux
									.interval(Duration.ofMillis(500))
									.map(tick -> {
										if (tick < data.size())
											return "item " + tick + ": " + data.get(tick.intValue());
										return "Done (tick == data.size())";
									});
		
		intervalFlux1.take(data.size() + 1).subscribe(System.out::println);
		Thread.sleep(3000);
		
		System.out.println("=== from Collection using zipWithIterable() and map() ===");
		Flux intervalFlux2 = Flux
									.interval(Duration.ofMillis(500))
									.zipWithIterable(data)
									.map(source -> "item " + source.getT1() + ": " + source.getT2());

		intervalFlux2.subscribe(System.out::println);
		Thread.sleep(3000);
		
		System.out.println("=== from Flux using zipWith() ===");
		Flux flux = Flux.just("{A}", "{B}", "{C}");
		Flux intervalFlux3 = Flux
									.interval(Duration.ofMillis(500))
									.zipWith(flux, (i, item) -> "item " + i + ": " + item);
		
		intervalFlux3.subscribe(System.out::println);
		Thread.sleep(3000);

	}
}

Run and check Results:

=== from Collection using map() ===
item 0: {A}
item 1: {B}
item 2: {C}
Done (tick == data.size())
=== from Collection using zipWithIterable() and map() ===
item 0: {A}
item 1: {B}
item 2: {C}
=== from Flux using zipWith() ===
item 0: {A}
item 1: {B}
item 2: {C}

32 thoughts on “Reactor – How to Create Flux (Publisher) with Interval”

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

  2. Very nice post. I just stumbled upon your blog and wished to say that I have really
    enjoyed browsing your blog posts. After all I will be subscribing to your feed and I hope you write again very soon!

  3. I blog quite often and I genuinely appreciate your content.
    Your article has really peaked my interest. I will bookmark your site
    and keep checking for new information about once a
    week. I subscribed to your RSS feed as well.

  4. Excellent pieces. Keep posting such kind of information on your page.

    Im really impressed by your site.
    Hey there, You’ve done an incredible job. I will certainly digg
    it and individually recommend to my friends. I am confident they’ll
    be benefited from this site.

  5. I am really enjoying the theme/design of your web site. Do you ever run into any browser compatibility issues? A couple of my blog readers have complained about my site not working correctly in Explorer but looks great in Safari. Do you have any ideas to help fix this problem?

  6. There are actually quite a lot of details like that to take into consideration. That is a great level to deliver up. I provide the thoughts above as common inspiration but clearly there are questions like the one you deliver up the place a very powerful thing will be working in sincere good faith. I don?t know if greatest practices have emerged around issues like that, but I’m certain that your job is clearly recognized as a good game. Each girls and boys feel the influence of only a moment抯 pleasure, for the remainder of their lives.

  7. A person essentially help to make seriously articles I would state. This is the first time I frequented your website page and thus far? I amazed with the research you made to create this particular publish incredible. Magnificent job!

  8. 768267 164694Nice post. I learn something much more challenging on different blogs everyday. It will always be stimulating to read content from other writers and practice a little something from their store. Id prefer to use some with the content on my weblog whether you dont mind. Natually Ill give you a link on your internet weblog. Thanks for sharing. 769643

  9. Thus try and constantly choose regular subscribe bonus and not
    the free play model – if you don’t want to exam the game with little deposit, having less
    probability of achievements.

  10. I’m impressed, I have to admit. Truly rarely must i encounter a weblog that’s both educative and entertaining, and without a doubt, you could have hit the nail for the head. Your notion is outstanding; the pain is a thing that too little people are speaking intelligently about. I’m very happy that we came across this during my try to find something about it.

  11. You actually make it seem really easy with your presentation however I find this matter to be actually something that I feel I might never understand. It kind of feels too complicated and very vast for me. I am taking a look forward on your subsequent post, I’ll attempt to get the grasp of it!

  12. Do you have a spam issue on this website; I also am a blogger, and I was wondering your situation; many of us have developed some nice procedures and we are looking to swap strategies with others, why not shoot me an email if interested.

  13. Thanks for every one of your efforts on this website. My daughter enjoys doing investigations and it is easy to see why. Almost all know all of the powerful way you present functional secrets via the web site and therefore improve contribution from visitors on that topic so our girl is always understanding a whole lot. Have fun with the rest of the year. You’re performing a first class job.

  14. Needed to write you the tiny note to finally say thanks again considering the superb solutions you have documented in this case. This has been simply incredibly open-handed of people like you to provide easily all that most people could have sold for an ebook to generate some cash on their own, principally considering that you could possibly have done it if you ever wanted. Those principles additionally acted to become a good way to fully grasp that other people have a similar dream just like mine to grasp a whole lot more related to this problem. I am certain there are lots of more enjoyable moments up front for individuals who view your blog post.

  15. hi!,I like your writing so much! share we communicate more about your post on AOL? I require an expert on this area to solve my problem. May be that’s you! Looking forward to see you.

  16. Hi, i think that i saw you visited my website thus i got here to “go back the choose”.I am attempting to to find things to enhance my site!I guess its ok to make use of a few of your ideas!!

Leave a Reply

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