By kswaughs | Tuesday, May 12, 2020

Spring Webflux Publisher Example

This post explains how to produce or generate flux of events programmatically.

In this example, we are publishing multiplication table of given number starting from 0 to 10 and subscriber is printing each event in console.

PublisherExample.java
package com.kswaughs.webflux;

import reactor.core.publisher.Flux;

public class PublisherExample {

    public Flux<String> produceTableOf(int num) {

        return Flux.generate(
            () -> 0, // Supplier of Initial State
            (state, sink) -> {

                if (state > 10) {
                    sink.complete();
                    return state;
                }

                String calc = num + " x " + state + " = " + num * state;
                sink.next(calc);
                return state + 1;
            }, 
            state -> {
                System.out.println("Final state:" + state);
            });
    }

    public static void main(String[] args) {

        PublisherExample example = new PublisherExample();

        System.out.println("*** Table of 5 ****");
        example.produceTableOf(5).subscribe(System.out::println);

        System.out.println("\n*** Table of 3 ****");
        example.produceTableOf(3).subscribe(System.out::println);
    }
}

Output

*** Table of 5 ****
5 x 0 = 0
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
Final state:11

*** Table of 3 ****
3 x 0 = 0
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3 x 5 = 15
3 x 6 = 18
3 x 7 = 21
3 x 8 = 24
3 x 9 = 27
3 x 10 = 30
Final state:11

Recommend this on


No comments:

Post a Comment