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

The following examples show how to use reactor.core.publisher.Flux#subscribe() . These examples are extracted from open source projects. 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
@Test // gh-22731
public void cancelWithProtobufDecoder() throws InterruptedException {
	ProtobufDecoder decoder = new ProtobufDecoder();

	Mono<DataBuffer> input = Mono.fromCallable(() -> {
		Msg msg = Msg.newBuilder().setFoo("Foo").build();
		byte[] bytes = msg.toByteArray();
		DataBuffer buffer = this.bufferFactory.allocateBuffer(bytes.length);
		buffer.write(bytes);
		return buffer;
	});

	Flux<Message> messages = decoder.decode(input, ResolvableType.forType(Msg.class),
			new MimeType("application", "x-protobuf"), Collections.emptyMap());
	ZeroDemandMessageSubscriber subscriber = new ZeroDemandMessageSubscriber();
	messages.subscribe(subscriber);
	subscriber.cancel();
}
 
Example 2
@Test
public void mergingMonos() throws Exception {
	//given
	final Mono<BigDecimal> fast = Mono
			.just(BigDecimal.valueOf(1))
			.delayElement(ofMillis(200));

	final Mono<BigDecimal> slow = Mono
			.just(BigDecimal.valueOf(2))
			.delayElement(ofMillis(100));

	//when
	final Flux<BigDecimal> merged = Flux.merge(
			fast,
			slow
	);

	//then
	merged.subscribe(d -> log.info("Received {}", d));
	TimeUnit.SECONDS.sleep(2);
}
 
Example 3
Source Project: camelinaction2   File: FirstTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testFirstVerbose() throws Exception {
    LOG.info("Starting Reactive-Core Flux first verbose mode");

    // create a publisher with just these words
    Publisher<String> publisher = Flux.just("Camel", "rocks", "streams", "as", "well");

    Flux<String> subscriber = Flux.from(publisher)
        // upper case the word
        .map(w -> w.toUpperCase())
        // log the big number
        .doOnNext(w -> LOG.info(w));

    // start the subscriber
    subscriber.subscribe();
}
 
Example 4
@Test
void givenTwoTerminationSubscribersWhenAnEventIsSentItShouldBeReceivedByBoth() {
    TerminationSubscriber subscriber1 = subscriber();
    TerminationSubscriber subscriber2 = subscriber();

    Flux<Event> firstListener = Flux.from(subscriber1.listenEvents());
    Flux<Event> secondListener = Flux.from(subscriber2.listenEvents());

    sendEvents(subscriber1, COMPLETED_EVENT);

    List<Event> receivedEventsFirst = new ArrayList<>();
    firstListener.subscribe(receivedEventsFirst::add);
    List<Event> receivedEventsSecond = new ArrayList<>();
    secondListener.subscribe(receivedEventsSecond::add);

    Awaitility.await().atMost(ONE_MINUTE).until(() -> receivedEventsFirst.size() == 1 && receivedEventsSecond.size() == 1);

    assertThat(receivedEventsFirst).containsExactly(COMPLETED_EVENT);
    assertThat(receivedEventsSecond).containsExactly(COMPLETED_EVENT);
}
 
Example 5
public static void main(String[] args) {
	
	Flux<String> fewWords = Flux.just("One","Two");
	
	/* from array */
	Flux<Integer> intFlux = Flux.fromArray(new Integer[]{1,2,3,4,5,6,7});
	
	/* from Java 8 stream  */
	Flux<String> strFlux = Flux.fromStream(Stream.of(
		"Ten", "Hundred", "Thousand", "Ten Thousands", "Lac","Ten Lac", "Crore"));
	
	/* from other Publisher */
	Flux<String> fromOtherPublisherFlux = Flux.from(fewWords);
	
	intFlux.subscribe(System.out::println);
	strFlux.subscribe(System.out::println);
	fromOtherPublisherFlux.subscribe(System.out::println);
}
 
Example 6
@Test
public void writeAsynchronousFileChannelCanceled() throws Exception {
	DataBuffer foo = stringBuffer("foo");
	DataBuffer bar = stringBuffer("bar");
	Flux<DataBuffer> flux = Flux.just(foo, bar);

	AsynchronousFileChannel channel =
			AsynchronousFileChannel.open(tempFile, StandardOpenOption.WRITE);

	Flux<DataBuffer> writeResult = DataBufferUtils.write(flux, channel);
	StepVerifier.create(writeResult, 1)
			.consumeNextWith(stringConsumer("foo"))
			.thenCancel()
			.verify();

	String result = String.join("", Files.readAllLines(tempFile));

	assertEquals("foo", result);
	channel.close();

	flux.subscribe(DataBufferUtils::release);
}
 
Example 7
@Test
public void simpleOnDiscardRequestChannelTest2() {
  ByteBufAllocator allocator = rule.alloc();
  AssertSubscriber<Payload> assertSubscriber = AssertSubscriber.create(1);
  TestPublisher<Payload> testPublisher = TestPublisher.create();

  Flux<Payload> payloadFlux = rule.socket.requestChannel(testPublisher);

  payloadFlux.subscribe(assertSubscriber);

  testPublisher.next(ByteBufPayload.create("d", "m"));

  int streamId = rule.getStreamIdForRequestType(REQUEST_CHANNEL);
  testPublisher.next(ByteBufPayload.create("d1", "m1"), ByteBufPayload.create("d2", "m2"));

  rule.connection.addToReceivedBuffer(
      ErrorFrameCodec.encode(
          allocator, streamId, new CustomRSocketException(0x00000404, "test")));

  Assertions.assertThat(rule.connection.getSent()).allMatch(ByteBuf::release);

  rule.assertHasNoLeaks();
}
 
Example 8
@Test
public void timestamp() throws Exception {
	//given
	final Flux<String> ticker = Flux
			.interval(ofMillis(123))
			.map(lng -> "Item-" + lng);

	//when
	final Flux<Tuple2<Long, String>> stamped = ticker.timestamp();

	//then
	final Flux<Tuple2<Instant, String>> instants = stamped
			.map(tup -> tup.mapT1(Instant::ofEpochMilli));

	instants
			.subscribe(
					x -> log.info("Received {}", x)
			);

	TimeUnit.SECONDS.sleep(4);
}
 
Example 9
Source Project: tutorials   File: FooService.java    License: MIT License 5 votes vote down vote up
public void processUsingApproachFourWithCheckpoint(Flux<Foo> flux) {
    logger.info("starting approach four!");
    flux = concatAndSubstringFooName(flux);
    flux = flux.checkpoint("CHECKPOINT 1");
    flux = concatAndSubstringFooName(flux);
    flux = divideFooQuantity(flux);
    flux = flux.checkpoint("CHECKPOINT 2", true);
    flux = reportResult(flux, "FOUR");
    flux = concatAndSubstringFooName(flux).doOnError(error -> {
        logger.error("Approach 4 failed!", error);
    });
    flux.subscribe();
}
 
Example 10
Source Project: tutorials   File: FluxUnitTest.java    License: MIT License 5 votes vote down vote up
@Test
public void whenFluxIsConstructed_thenCorrect() {
    final Flux<Foo> flux = Flux.<Foo> create(fluxSink -> {
        for (int i = 0 ; i < 100 ; i++) {
            fluxSink.next(new Foo(RANDOM.nextLong(), randomAlphabetic(6)));
        }
    }).sample(Duration.ofSeconds(1)).log();

    flux.subscribe();

    assertNotNull(flux);
}
 
Example 11
@Test
public void releaseConsumer() {
	DataBuffer foo = stringBuffer("foo");
	DataBuffer bar = stringBuffer("bar");
	DataBuffer baz = stringBuffer("baz");
	Flux<DataBuffer> flux = Flux.just(foo, bar, baz);

	flux.subscribe(DataBufferUtils.releaseConsumer());

	assertReleased(foo);
	assertReleased(bar);
	assertReleased(baz);
}
 
Example 12
@Test // gh-22107
public void cancelWithJackson() {
	Jackson2JsonEncoder encoder = new Jackson2JsonEncoder();

	Flux<DataBuffer> flux = encoder.encode(Flux.just(new Pojo("foofoo", "barbar"), new Pojo("bar", "baz")),
			this.bufferFactory, ResolvableType.forClass(Pojo.class),
			MediaType.APPLICATION_JSON, Collections.emptyMap());

	BaseSubscriber<DataBuffer> subscriber = new ZeroDemandSubscriber();
	flux.subscribe(subscriber); // Assume sync execution (e.g. encoding with Flux.just)..
	subscriber.cancel();
}
 
Example 13
Source Project: tutorials   File: FooService.java    License: MIT License 5 votes vote down vote up
public void processUsingApproachFivePublishingToDifferentSingleThreads(Flux<Foo> flux) {
    logger.info("starting approach five-single!");
    flux = flux.log()
        .subscribeOn(Schedulers.newSingle("five-single-starter"));
    flux = concatAndSubstringFooName(flux).publishOn(Schedulers.newSingle("five-single-foo"));
    flux = concatAndSubstringFooName(flux);
    flux = divideFooQuantity(flux);
    flux = reportResult(flux, "FIVE-SINGLE").publishOn(Schedulers.newSingle("five-single-bar"));
    flux = concatAndSubstringFooName(flux).doOnError(error -> {
        logger.error("Approach 5-single failed!", error);
    });
    flux.subscribe();
}
 
Example 14
Source Project: reactor-pool   File: SimpleFifoPoolTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void demonstrateAcquireInScopePipeline() throws InterruptedException {
    AtomicInteger counter = new AtomicInteger();
    AtomicReference<String> releaseRef = new AtomicReference<>();

    SimpleFifoPool<String> pool = new SimpleFifoPool<>(
            from(Mono.just("Hello Reactive World"))
                    .sizeBetween(0, 1)
                    .releaseHandler(s -> Mono.fromRunnable(()-> releaseRef.set(s)))
                    .buildConfig());

    Flux<String> words = pool.withPoolable(poolable -> Mono.just(poolable)
            //simulate deriving a value from the resource (ie. query from DB connection)
            .map(resource -> resource.split(" "))
            //then further process the derived value to produce multiple values (ie. rows from a query)
            .flatMapIterable(Arrays::asList)
            //and all that with latency
            .delayElements(Duration.ofMillis(500)));

    words.subscribe(v -> counter.incrementAndGet());
    assertThat(counter).hasValue(0);

    Thread.sleep(1100);
    //we're in the middle of processing the "rows"
    assertThat(counter).as("before all emitted").hasValue(2);
    assertThat(releaseRef).as("still acquiring").hasValue(null);

    Thread.sleep(500);
    //we've finished processing, let's check resource has been automatically released
    assertThat(counter).as("after all emitted").hasValue(3);
    assertThat(pool.poolConfig.allocationStrategy().estimatePermitCount()).as("allocation permits").isZero();
    assertThat(pool.elements).as("available").hasSize(1);
    assertThat(releaseRef).as("released").hasValue("Hello Reactive World");
}
 
Example 15
Source Project: tutorials   File: FooService.java    License: MIT License 5 votes vote down vote up
public void processUsingApproachFourWithInitialCheckpoint(Flux<Foo> flux) {
    logger.info("starting approach four!");
    flux = concatAndSubstringFooName(flux);
    flux = flux.checkpoint("CHECKPOINT 1", true);
    flux = concatAndSubstringFooName(flux);
    flux = divideFooQuantity(flux);
    flux = reportResult(flux, "FOUR");
    flux = flux.doOnError(error -> {
        logger.error("Approach 4-2 failed!", error);
    });
    flux.subscribe();
}
 
Example 16
@Override
public void saveAllRateLimitRules(Flux<RateLimitRule> rateLimitRules) {
    rateLimitRules.subscribe(r -> {
        String key = RouteEnhanceCacheUtil.getRateLimitCacheKey(r.getRequestUri(), r.getRequestMethod());
        String value = JSONObject.toJSONString(r);
        redisService.set(key, value);
    });
    log.info("Cache rate limit rules into redis >>>");
}
 
Example 17
Source Project: reactor-core   File: PublisherProbeTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void wasSubscribedNumberFlux() {
	PublisherProbe<Void> probe = PublisherProbe.empty();
	Flux<Void> mono = probe.flux();

	assertThat(probe.subscribeCount()).isEqualTo(0);

	mono.subscribe();
	assertThat(probe.subscribeCount()).isEqualTo(1);

	mono.subscribe();
	assertThat(probe.subscribeCount()).isEqualTo(2);
}
 
Example 18
Source Project: reactor-core   File: MonoTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testMonoThenManySupplier() {
	AssertSubscriber<String> ts = AssertSubscriber.create();
	Flux<String> test = Mono.just(1).thenMany(Flux.defer(() -> Flux.just("A", "B")));

	test.subscribe(ts);
	ts.assertValues("A", "B");
	ts.assertComplete();
}
 
Example 19
Source Project: spring-5-examples   File: FluxSinkApplication.java    License: MIT License 5 votes vote down vote up
@Bean
ApplicationRunner handler(final Flux<ServerSentEvent<Map>> processor,
                          final Consumer<ServerSentEvent<Map>> onNextConsumer,
                          final Consumer<Throwable> onErrorConsumer,
                          final Runnable completeConsumer) {

  return args -> processor.subscribe(
      onNextConsumer,
      onErrorConsumer,
      completeConsumer
  );
}
 
Example 20
public static void main(String[] args) {

		Flux<String> hrUsers = Flux.fromStream(Stream.of(
				"John", "Komal", "Harmi", "Bhakti", "Tom","Peter"));
		
		CustomSubscriber cs = new CustomSubscriber();
		
		hrUsers.subscribe(cs);
	}