reactor.core.publisher.ConnectableFlux Java Examples

The following examples show how to use reactor.core.publisher.ConnectableFlux. 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: ConnectConnect.java    From akarnokd-misc with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 5000)
public void schedulerTest() throws InterruptedException {
  CountDownLatch latch = new CountDownLatch(2);

  ConnectableFlux<Integer> connectableFlux = just(1, 2, 3, 4, 5).publish();

  connectableFlux
      .log()
      .subscribe(v -> {} , e -> {}, latch::countDown);

  connectableFlux
      .publishOn(parallel())
      .log()
      .map(v -> v * 10)
      .publishOn(single())
      .log()
      .subscribeOn(elastic())
      .subscribe(v -> {} , e -> {}, latch::countDown);

  Thread.sleep(100);

  connectableFlux.connect();
  latch.await();
}
 
Example #2
Source File: GuideTests.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void advancedConnectable() throws InterruptedException {
	Flux<Integer> source = Flux.range(1, 3)
	                           .doOnSubscribe(s -> System.out.println("subscribed to source"));

	ConnectableFlux<Integer> co = source.publish();

	co.subscribe(System.out::println, e -> {}, () -> {});
	co.subscribe(System.out::println, e -> {}, () -> {});

	System.out.println("done subscribing");
	Thread.sleep(500);
	System.out.println("will now connect");

	co.connect();
}
 
Example #3
Source File: HooksTraceTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultiReceiver() {
	Hooks.onOperatorDebug();
	ConnectableFlux<?> t = Flux.empty()
	    .then(Mono.defer(() -> {
		    throw new RuntimeException();
	    })).flux().publish();

	t.map(d -> d).subscribe(null,
			e -> assertThat(e.getSuppressed()[0].getMessage()).contains("\t|_ Flux.publish"));

	t.filter(d -> true).subscribe(null, e -> {
		assertThat(e.getSuppressed()[0].getMessage()).contains("\t|_____ Flux.publish");
	});
	t.distinct().subscribe(null, e -> {
		assertThat(e.getSuppressed()[0].getMessage()).contains("\t|_________  Flux.publish");
	});

	t.connect();
}
 
Example #4
Source File: ReactorEssentialsTest.java    From Hands-On-Reactive-Programming-in-Spring-5 with MIT License 5 votes vote down vote up
@Test
public void connectExample() {
    Flux<Integer> source = Flux.range(0, 3)
        .doOnSubscribe(s ->
            log.info("new subscription for the cold publisher"));

    ConnectableFlux<Integer> conn = source.publish();

    conn.subscribe(e -> log.info("[Subscriber 1] onNext: {}", e));
    conn.subscribe(e -> log.info("[Subscriber 2] onNext: {}", e));

    log.info("all subscribers are ready, connecting");
    conn.connect();
}
 
Example #5
Source File: EmojiTrackerStubController.java    From reactor-workshop with GNU General Public License v3.0 5 votes vote down vote up
public EmojiTrackerStubController() {
    final ConnectableFlux<String> flux = Flux
            .fromStream(() -> openFile("/emojis.txt").lines())
            .repeat()
            .zipWith(Flux.interval(Duration.ofMillis(25)))
            .map(Tuple2::getT1)
            .publish();
    flux.connect();
    stream = flux;
}
 
Example #6
Source File: EmployeeHotStreamServiceImpl.java    From Spring-5.0-Cookbook with MIT License 5 votes vote down vote up
@Override
public ConnectableFlux<String> freeFlowEmps() {
	 Vector<String> rosterNames = new Vector<>();
	 Function<Employee, String> familyNames = (emp) -> emp.getLastName().toUpperCase();
	 ConnectableFlux<String> flowyNames = Flux.fromIterable(employeeDaoImpl.getEmployees()).log().map(familyNames).cache().publish();
	// flowyNames.subscribe(System.out::println);
	 flowyNames.subscribe(rosterNames::add);
	 System.out.println(rosterNames);
	return flowyNames;
}
 
Example #7
Source File: EsPublisher.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
@Override
public void activate() {
    ConnectableFlux<TaskDocument> taskEvents = taskEventsGenerator.getTaskEvents();
    subscription = taskEvents.bufferTimeout(100, Duration.ofSeconds(5))
            .flatMap(taskDocuments ->
                            esClient.bulkIndexDocuments(
                                    taskDocuments,
                                    ElasticSearchUtils.buildEsIndexNameCurrent(esPublisherConfiguration.getTaskDocumentEsIndexName(), indexDateFormat),
                                    ES_RECORD_TYPE)
                                    .retryWhen(TaskPublisherRetryUtil.buildRetryHandler(
                                            TaskPublisherRetryUtil.INITIAL_RETRY_DELAY_MS,
                                            TaskPublisherRetryUtil.MAX_RETRY_DELAY_MS, 3)),
                    MAX_CONCURRENCY)
            .doOnError(e -> {
                logger.error("Error in indexing documents (Retrying) : ", e);
                numErrors.incrementAndGet();
            })
            .retryWhen(TaskPublisherRetryUtil.buildRetryHandler(TaskPublisherRetryUtil.INITIAL_RETRY_DELAY_MS,
                    TaskPublisherRetryUtil.MAX_RETRY_DELAY_MS, -1))
            .subscribe(bulkIndexResp -> {
                        logger.info("Received bulk response for {} items", bulkIndexResp.getItems().size());
                        lastPublishedTimestamp.set(registry.clock().wallTime());
                        bulkIndexResp.getItems().forEach(bulkEsIndexRespItem -> {
                            String indexedItemId = bulkEsIndexRespItem.getIndex().getId();
                            logger.info("Index result <{}> for task ID {}", bulkEsIndexRespItem.getIndex().getResult(), indexedItemId);
                            numTasksUpdated.incrementAndGet();
                        });
                    },
                    e -> logger.error("Error in indexing documents ", e));
    taskEventsSourceConnection = taskEvents.connect();
}
 
Example #8
Source File: CustomSourceSnippets.java    From reactor-by-example with MIT License 5 votes vote down vote up
@Test
public void create() throws InterruptedException {
	SomeFeed<PriceTick> feed = new SomeFeed<>();
	Flux<PriceTick> flux =
			Flux.create(emitter ->
			{
				SomeListener listener = new SomeListener() {
					@Override
					public void priceTick(PriceTick event) {
						emitter.next(event);
						if (event.isLast()) {
							emitter.complete();
						}
					}

					@Override
					public void error(Throwable e) {
						emitter.error(e);
					}};
				feed.register(listener);
			}, FluxSink.OverflowStrategy.BUFFER);

	ConnectableFlux<PriceTick> hot = flux.publish();

	hot.subscribe(priceTick -> System.out.printf("%s %4s %6.2f%n", priceTick
			.getDate(), priceTick.getInstrument(), priceTick.getPrice()));

	hot.subscribe(priceTick -> System.out.println(priceTick.getSequence() +
			": " + priceTick.getInstrument()));
	hot.connect();
	Thread.sleep(5000);
}
 
Example #9
Source File: GenericEvent.java    From linstor-server with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void triggerEvent(ObjectIdentifier objectIdentifier, T value)
{
    Flux<T> stream = null;
    FluxSink<T> sink;
    Set<FluxSink<Tuple2<ObjectIdentifier, Flux<T>>>> waiterSet = null;

    lock.lock();
    try
    {
        sink = sinks.get(objectIdentifier);
        if (sink == null)
        {
            UnicastProcessor<T> processor = UnicastProcessor.create();
            ConnectableFlux<T> publisher = processor.replay(1);
            publisher.connect();

            // Publish events signals on the main scheduler to detach the execution from this thread,
            // so that we don't react to events in the thread-local context where the event is triggered.
            stream = publisher.publishOn(scheduler);
            streams.put(objectIdentifier, stream);
            try
            {
                eventStreamStore.addEventStream(new EventIdentifier(null, objectIdentifier));
            }
            catch (LinStorDataAlreadyExistsException exc)
            {
                throw new ImplementationError(exc);
            }

            sink = processor.sink();
            sinks.put(objectIdentifier, sink);

            List<ObjectIdentifier> matchingWaitObjects = matchingObjects(objectIdentifier);

            waiterSet = new HashSet<>();
            for (ObjectIdentifier waitObject : matchingWaitObjects)
            {
                Set<FluxSink<Tuple2<ObjectIdentifier, Flux<T>>>> waitersForObject = waiters.get(waitObject);
                if (waitersForObject != null)
                {
                    waiterSet.addAll(waitersForObject);
                }
            }
        }
    }
    finally
    {
        lock.unlock();
    }

    if (waiterSet != null)
    {
        for (FluxSink<Tuple2<ObjectIdentifier, Flux<T>>> waiter : waiterSet)
        {
            waiter.next(Tuples.of(objectIdentifier, stream));
        }
    }

    sink.next(value);
}
 
Example #10
Source File: TaskEventsGenerator.java    From titus-control-plane with Apache License 2.0 4 votes vote down vote up
public ConnectableFlux<TaskDocument> getTaskEvents() {
    return taskEvents;
}
 
Example #11
Source File: ReactorIntegrationTest.java    From tutorials with MIT License 3 votes vote down vote up
@Test
public void givenConnectableFlux_whenConnected_thenShouldStream() {

    List<Integer> elements = new ArrayList<>();

    final ConnectableFlux<Integer> publish = Flux.just(1, 2, 3, 4).publish();

    publish.subscribe(elements::add);

    assertThat(elements).isEmpty();

    publish.connect();

    assertThat(elements).containsExactly(1, 2, 3, 4);
}
 
Example #12
Source File: EmployeeHotStreamService.java    From Spring-5.0-Cookbook with MIT License votes vote down vote up
public ConnectableFlux<String> freeFlowEmps();