Java Code Examples for reactor.core.publisher.Flux#generate()

The following examples show how to use reactor.core.publisher.Flux#generate() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SchedulerTest.java    From Hands-On-Reactive-Programming-with-Reactor with MIT License 6 votes vote down vote up
@Test
public void testElasticScheduler() throws Exception{
    Flux<Long> fibonacciGenerator = Flux.generate(() -> Tuples.<Long,
            Long>of(0L, 1L), (state, sink) -> {
        if (state.getT1() < 0)
            sink.complete();
        else
            sink.next(state.getT1());
        print("Generating next of "+ state.getT2());

        return Tuples.of(state.getT2(), state.getT1() + state.getT2());
    });
    fibonacciGenerator
            .filter(x -> {
                print("Executing Filter");
                return x < 100;
            }).delayElements(Duration.ZERO,Schedulers.elastic())
            .window(10)
            .doOnNext(x -> print("Next value is  "+ x))
            .doFinally(x -> print("Closing "+x))
            .subscribe(x -> print("Sub received : "+x.blockFirst()));
    Thread.sleep(500);
}
 
Example 2
Source File: SchedulerTest.java    From Hands-On-Reactive-Programming-with-Reactor with MIT License 6 votes vote down vote up
@Test
public void testParallelScheduler() throws Exception{
    Flux<Long> fibonacciGenerator = Flux.generate(() -> Tuples.<Long,
            Long>of(0L, 1L), (state, sink) -> {
        if (state.getT1() < 0)
            sink.complete();
        else
            sink.next(state.getT1());
        print("Generating next of "+ state.getT2());

        return Tuples.of(state.getT2(), state.getT1() + state.getT2());
    });
    fibonacciGenerator
            .filter(x -> {
                print("Executing Filter");
                return x < 100;
            }).delayElements(Duration.ZERO,Schedulers.parallel())
             .doOnNext(x -> print("Next value is  "+ x))
            .doFinally(x -> print("Closing "+x))
            .subscribe(x -> print("Sub received : "));
    Thread.sleep(500);
}
 
Example 3
Source File: EmployeeWebSocketHandler.java    From tutorials with MIT License 6 votes vote down vote up
@Override
public Mono<Void> handle(WebSocketSession webSocketSession) {

    Flux<String> employeeCreationEvent = Flux.generate(sink -> {
        EmployeeCreationEvent event = new EmployeeCreationEvent(randomUUID().toString(), now().toString());
        try {
            sink.next(om.writeValueAsString(event));
        } catch (JsonProcessingException e) {
            sink.error(e);
        }
    });

    return webSocketSession.send(employeeCreationEvent
        .map(webSocketSession::textMessage)
        .delayElements(Duration.ofSeconds(1)));
}
 
Example 4
Source File: ReactorTest.java    From Hands-On-Reactive-Programming-with-Reactor with MIT License 6 votes vote down vote up
@Test
public void testRecordWith() throws Exception {
    Flux<Long> fibonacciGenerator = Flux.generate(() -> Tuples.<Long,
            Long>of(0L, 1L), (state, sink) -> {
        if (state.getT1() < 0)
            sink.complete();
        else
            sink.next(state.getT1());
        System.out.println("generating next of " + state.getT2());

        return Tuples.of(state.getT2(), state.getT1() + state.getT2());
    });

    StepVerifier.create(fibonacciGenerator, Long.MAX_VALUE)
            .recordWith(() -> new ArrayList<>())
            .thenConsumeWhile(x -> x >= 0)
            .expectRecordedMatches(x -> x.size() > 0)
            .expectComplete()
            .verify();
}
 
Example 5
Source File: ReactorTest.java    From Hands-On-Reactive-Programming-with-Reactor with MIT License 6 votes vote down vote up
@Test
public void testFibonacci() {
    Flux<Long> fibonacciGenerator = Flux.generate(
            () -> Tuples.<Long, Long>of(0L, 1L),
            (state, sink) -> {
                sink.next(state.getT1());
                return Tuples.of(state.getT2(), state.getT1() + state.getT2());
            });
    List<Long> fibonacciSeries = new LinkedList<>();
    int size = 50;
    fibonacciGenerator.take(size).subscribe(t -> {
        fibonacciSeries.add(t);
    });
    System.out.println(fibonacciSeries);
    assertEquals( 7778742049L, fibonacciSeries.get(size-1).longValue());
}
 
Example 6
Source File: ErrorHandlingTest.java    From Hands-On-Reactive-Programming-with-Reactor with MIT License 6 votes vote down vote up
@Test
public void testUsingMethod() {
    Flux<Long> fibonacciGenerator = Flux.generate(() -> Tuples.<Long,
            Long>of(0L, 1L), (state, sink) -> {
        if (state.getT1() < 0)
            sink.complete();
        else
            sink.next(state.getT1());

        return Tuples.of(state.getT2(), state.getT1() + state.getT2());
    });
    Closeable closable = () -> System.out.println("closing the stream");
    Flux.using(() -> closable, x -> fibonacciGenerator, e -> {
        try {
            e.close();
        } catch (Exception e1) {
            throw Exceptions.propagate(e1);
        }
    }).subscribe(System.out::println);
}
 
Example 7
Source File: ReactorProbe.java    From Hands-On-Reactive-Programming-with-Reactor with MIT License 6 votes vote down vote up
@Test
public void testPublisherProbe() throws Exception {
    Flux<Long> fibonacciGenerator = Flux.generate(() -> Tuples.<Long,
            Long>of(0L, 1L), (state, sink) -> {
        if (state.getT1() < 0)
            sink.complete();
        else
            sink.next(state.getT1());
        return Tuples.of(state.getT2(), state.getT1() + state.getT2());
    });

    PublisherProbe<Long> publisherProbe = PublisherProbe.of(fibonacciGenerator);
    publisherProbe.flux().subscribe();

    publisherProbe.assertWasSubscribed();
    publisherProbe.assertWasRequested();

}
 
Example 8
Source File: TimeoutTest.java    From Hands-On-Reactive-Programming-with-Reactor with MIT License 6 votes vote down vote up
@Test
public void testTimeout() throws  Exception{
    Flux<Long> fibonacciGenerator = Flux.generate(() -> Tuples.<Long,
            Long>of(0L, 1L), (state, sink) -> {
        if (state.getT1() < 0)
            throw new RuntimeException("Value out of bounds");
        else
            sink.next(state.getT1());

        return Tuples.of(state.getT2(), state.getT1() + state.getT2());
    });
    CountDownLatch countDownLatch = new CountDownLatch(1);
    fibonacciGenerator
            .delayElements(Duration.ofSeconds(1))
            .timeout(Duration.ofMillis(500))
            .subscribe(System.out::println, e -> {
                System.out.println(e);
                countDownLatch.countDown();
            });
    countDownLatch.await();
}
 
Example 9
Source File: SchedulerTest.java    From Hands-On-Reactive-Programming-with-Reactor with MIT License 6 votes vote down vote up
@Test
public void testReactorComposite() throws Exception{
    Flux<Long> fibonacciGenerator = Flux.generate(() -> Tuples.<Long,
            Long>of(0L, 1L), (state, sink) -> {
        if (state.getT1() < 0)
            sink.complete();
        else
            sink.next(state.getT1());
        print("Generating next of "+ state.getT2());

        return Tuples.of(state.getT2(), state.getT1() + state.getT2());
    });
    fibonacciGenerator
            .publishOn(Schedulers.single())
         //   .delayElements(Duration.ZERO)
            .filter(x -> {
                print("Executing Filter");
                return x < 100;
            })
            .doOnNext(x -> print("Next value is  "+x))
            .doFinally(x -> print("Closing "))
            .subscribeOn(Schedulers.single())
            .subscribe(x -> print("Sub received : "+x));
    Thread.sleep(500);
}
 
Example 10
Source File: ReactorTest.java    From Hands-On-Reactive-Programming-with-Reactor with MIT License 6 votes vote down vote up
@Test
public void testFibonacciSkip() {
    Flux<Long> fibonacciGenerator = Flux.generate(
            () -> Tuples.<Long, Long>of(0L, 1L),
            (state, sink) -> {
                if (state.getT1() < 0) {
                    sink.error(new RuntimeException("Negative number found"));
                } else {
                    sink.next(state.getT1());
                }
                return Tuples.of(state.getT2(), state.getT1() + state.getT2());
            });

    fibonacciGenerator.skip(10).subscribe(t -> {
        System.out.println(t);
    });
    fibonacciGenerator.skip(Duration.ofMillis(10)).subscribe(t -> {
        System.out.println(t);
    });
    fibonacciGenerator.skipUntil(t -> (t > 100)).subscribe(t -> {
        System.out.println(t);
    });

}
 
Example 11
Source File: TimeoutTest.java    From Hands-On-Reactive-Programming-with-Reactor with MIT License 6 votes vote down vote up
@Test
public void testTimeoutWithFallback() throws  Exception{
    Flux<Long> fibonacciGenerator = Flux.generate(() -> Tuples.<Long,
            Long>of(0L, 1L), (state, sink) -> {
        if (state.getT1() < 0)
            throw new RuntimeException("Value out of bounds");
        else
            sink.next(state.getT1());

        return Tuples.of(state.getT2(), state.getT1() + state.getT2());
    });
    CountDownLatch countDownLatch = new CountDownLatch(1);
    fibonacciGenerator
            .delayElements(Duration.ofSeconds(1))
            .timeout(Duration.ofMillis(500),Flux.just(-1L))
            .subscribe(e -> {
                System.out.println("Received :"+e);
                countDownLatch.countDown();
            });
    countDownLatch.await();
}
 
Example 12
Source File: ReactorDemo.java    From reactive-streams-in-java with Apache License 2.0 5 votes vote down vote up
public static Flux<Long> exampleSquaresUsingGenerate() {
    Flux<Long> squares = Flux.generate(
            AtomicLong::new, //1
            (state, sink) -> {
                long i = state.getAndIncrement();
                sink.next(i * i); //2
                if (i == 10) sink.complete(); //3
                return state;
            });
    return squares;
}
 
Example 13
Source File: WindowTest.java    From Hands-On-Reactive-Programming-with-Reactor with MIT License 5 votes vote down vote up
@Test
public  void testWindowsFixedSize(){
    Flux<Long> fibonacciGenerator = Flux.generate(() -> Tuples.<Long,
            Long>of(0L, 1L), (state, sink) -> {
        if (state.getT1() < 0)
            sink.complete();
        else
            sink.next(state.getT1());
        return Tuples.of(state.getT2(), state.getT1() + state.getT2());
    });
    fibonacciGenerator
            .window(10)
            .concatMap(x -> x)
            .subscribe(x -> System.out.print(x+" "));
}
 
Example 14
Source File: ReactorTest.java    From Hands-On-Reactive-Programming-with-Reactor with MIT License 5 votes vote down vote up
@Test
public void testFibonacciConcat() {
    Flux<Long> fibonacciGenerator = Flux.generate(
            () -> Tuples.<Long, Long>of(0L, 1L),
            (state, sink) -> {
                sink.next(state.getT1());
                return Tuples.of(state.getT2(), state.getT1() + state.getT2());
            });
    fibonacciGenerator.take(10).concatWith(Flux.just(new Long[]{-1L, -2L, -3L, -4L})).subscribe(t -> {
        System.out.println(t);
    });

}
 
Example 15
Source File: ReactiveController.java    From Hands-On-Reactive-Programming-with-Reactor with MIT License 5 votes vote down vote up
@GetMapping(value = "/numbers1", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<Long>  handleSeries1() {
    Flux<Long> fibonacciGenerator = Flux.generate(() -> Tuples.<Long,
            Long>of(0L, 1L), (state, sink) -> {
        if (state.getT1() < 0)
            sink.complete();
        else
            sink.next(state.getT1());
        System.out.println("numbers1 generated :"+state.getT1());
        return Tuples.of(state.getT2(), state.getT1() + state.getT2());
    });
    return fibonacciGenerator.delayElements(Duration.ofSeconds(1));
}
 
Example 16
Source File: ReactorTest.java    From Hands-On-Reactive-Programming-with-Reactor with MIT License 5 votes vote down vote up
@Test
public void testFibonacciMap() {
    Flux<Long> fibonacciGenerator = Flux.generate(
            () -> Tuples.<Long, Long>of(0L, 1L),
            (state, sink) -> {
                sink.next(state.getT1());
                return Tuples.of(state.getT2(), state.getT1() + state.getT2());
            });
    RomanNumber numberConvertor = new RomanNumber();
    fibonacciGenerator.skip(1).take(10).map(t -> numberConvertor.toRoman(t.intValue())).subscribe(t -> {
        System.out.println(t);
    });

}
 
Example 17
Source File: ReactorTest.java    From Hands-On-Reactive-Programming-with-Reactor with MIT License 5 votes vote down vote up
@Test
public void testFibonacciFactorization() {
    Flux<Long> fibonacciGenerator = Flux.generate(
            () -> Tuples.<Long, Long>of(0L, 1L),
            (state, sink) -> {
                sink.next(state.getT1());
                return Tuples.of(state.getT2(), state.getT1() + state.getT2());
            });
    Factorization numberConvertor = new Factorization();
    fibonacciGenerator.skip(1).take(10).flatMap(t -> Flux.fromIterable(numberConvertor.findfactor(t.intValue()))).subscribe(t -> {
        System.out.println(t);
    });

}
 
Example 18
Source File: RetrySpecTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void builderCanBeUsedAsTemplate() {
	//a base builder can be reused across several Flux with different tuning for each flux
	RetrySpec template = Retry.max(1).transientErrors(false);

	Supplier<Flux<Integer>> transientError = () -> {
		AtomicInteger errorOnEven = new AtomicInteger();
		return Flux.generate(sink -> {
			int i = errorOnEven.getAndIncrement();
			if (i == 5) {
				sink.complete();
			}
			if (i % 2 == 0) {
				sink.error(new IllegalStateException("boom " + i));
			}
			else {
				sink.next(i);
			}
		});
	};

	Flux<Integer> modifiedTemplate1 = transientError.get().retryWhen(template.maxAttempts(2));
	Flux<Integer> modifiedTemplate2 = transientError.get().retryWhen(template.transientErrors(true));

	StepVerifier.create(modifiedTemplate1, StepVerifierOptions.create().scenarioName("modified template 1"))
	            .expectNext(1, 3)
	            .verifyErrorSatisfies(t -> assertThat(t)
			            .isInstanceOf(IllegalStateException.class)
			            .hasMessage("Retries exhausted: 2/2")
			            .hasCause(new IllegalStateException("boom 4")));

	StepVerifier.create(modifiedTemplate2, StepVerifierOptions.create().scenarioName("modified template 2"))
	            .expectNext(1, 3)
	            .verifyComplete();
}
 
Example 19
Source File: ReactorTest.java    From Hands-On-Reactive-Programming-with-Reactor with MIT License 5 votes vote down vote up
@Test
public void testFibonacciLogicalOperator() {
    Flux<Long> fibonacciGenerator = Flux.generate(
            () -> Tuples.<Long, Long>of(0L, 1L),
            (state, sink) -> {
                sink.next(state.getT1());
                return Tuples.of(state.getT2(), state.getT1() + state.getT2());
            });
    fibonacciGenerator.take(10).all(x -> x > 0).subscribe(t -> {
        System.out.println(t);
    });
}
 
Example 20
Source File: StatelessGenerate.java    From tutorials with MIT License 4 votes vote down vote up
public Flux<String> statelessGenerate() {
    return Flux.generate((sink) -> {
        sink.next("hello");
    });
}