io.smallrye.mutiny.Multi Java Examples
The following examples show how to use
io.smallrye.mutiny.Multi.
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: MultiOnFailureRetryWhenTest.java From smallrye-mutiny with Apache License 2.0 | 7 votes |
Multi<String> getMultiWithManualExponentialRetry() { AtomicInteger i = new AtomicInteger(); return Multi.createFrom().<String> emitter(s -> { if (i.incrementAndGet() == 4) { s.emit("hey"); } else { s.fail(new RuntimeException("test " + i)); } }).onFailure().retry().when( repeat -> { return Multi.createBy().combining().streams(repeat, Multi.createFrom().range(1, 4)).asTuple() .map(Tuple2::getItem2) .onItem().produceUni(time -> Uni.createFrom().item(time) .onItem().delayIt().by(Duration.ofMillis(time))) .concatenate(); }); }
Example #2
Source File: ReflectionService.java From quarkus with Apache License 2.0 | 6 votes |
@Override public Multi<ServerReflectionResponse> serverReflectionInfo(Multi<ServerReflectionRequest> request) { return request .onItem().apply(new Function<ServerReflectionRequest, ServerReflectionResponse>() { @Override public ServerReflectionResponse apply(ServerReflectionRequest req) { switch (req.getMessageRequestCase()) { case LIST_SERVICES: return ReflectionService.this.getServiceList(req); case FILE_BY_FILENAME: return ReflectionService.this.getFileByName(req); case FILE_CONTAINING_SYMBOL: return ReflectionService.this.getFileContainingSymbol(req); case FILE_CONTAINING_EXTENSION: return ReflectionService.this.getFileByExtension(req); case ALL_EXTENSION_NUMBERS_OF_TYPE: return ReflectionService.this.getAllExtensions(req); default: return ReflectionService.this.getErrorResponse(req, Status.Code.UNIMPLEMENTED, "not implemented " + req.getMessageRequestCase()); } } }); }
Example #3
Source File: MultiRepetitionTest.java From smallrye-mutiny with Apache License 2.0 | 6 votes |
@Test public void testWithUni() { AtomicInteger shared = new AtomicInteger(); Multi<Integer> multi = Multi.createBy().repeating() .uni(() -> Uni.createFrom().item(shared.incrementAndGet())) .atMost(2); assertThat(shared).hasValue(0); MultiAssertSubscriber<Integer> subscriber = multi.subscribe() .withSubscriber(MultiAssertSubscriber.create(1)); subscriber.assertReceived(1); assertThat(shared).hasValue(1); subscriber.request(1); subscriber.assertCompletedSuccessfully().assertReceived(1, 2); }
Example #4
Source File: ServerCalls.java From quarkus with Apache License 2.0 | 6 votes |
public static <I, O> StreamObserver<I> manyToOne(StreamObserver<O> response, Function<Multi<I>, Uni<O>> implementation) { try { UnicastProcessor<I> input = UnicastProcessor.create(); StreamObserver<I> pump = getStreamObserverFeedingProcessor(input); Uni<O> uni = implementation.apply(input); uni.subscribe().with( new Consumer<O>() { @Override public void accept(O item) { response.onNext(item); response.onCompleted(); } }, new Consumer<Throwable>() { @Override public void accept(Throwable failure) { response.onError(toStatusFailure(failure)); } }); return pump; } catch (Throwable throwable) { response.onError(toStatusFailure(throwable)); return null; } }
Example #5
Source File: AmqpSinkTest.java From smallrye-reactive-messaging with Apache License 2.0 | 6 votes |
@Test public void testCreditBasedFlowControl() { String topic = UUID.randomUUID().toString(); AtomicInteger expected = new AtomicInteger(0); usage.consumeIntegers(topic, v -> expected.getAndIncrement()); SubscriberBuilder<? extends Message<?>, Void> sink = createProviderAndSink(topic); //noinspection unchecked Multi.createFrom().range(0, 5000) .map(Message::of) .subscribe((Subscriber<? super Message<Integer>>) sink.build()); await().until(() -> expected.get() == 5000); assertThat(expected).hasValue(5000); }
Example #6
Source File: MultiFlattenTest.java From smallrye-mutiny with Apache License 2.0 | 6 votes |
@Test public void testWithMultisWithOneEmittingAFailure() { AtomicBoolean subscribed = new AtomicBoolean(); MultiAssertSubscriber<String> subscriber = Multi.createFrom().items( Multi.createFrom().items("a", "b", "c"), Multi.createFrom().items("d", "e"), Multi.createFrom().emitter(e -> { e.emit("f"); e.fail(new IOException("boom")); }), Multi.createFrom().items("g") .on().subscribed(s -> subscribed.set(true))) .onItem().<String> disjoint() .subscribe().withSubscriber(MultiAssertSubscriber.create(4)); assertThat(subscribed).isFalse(); subscriber.assertReceived("a", "b", "c", "d"); subscriber.request(3); subscriber.assertHasFailedWith(IOException.class, "boom"); assertThat(subscribed).isFalse(); }
Example #7
Source File: MultiSubscribeTest.java From smallrye-mutiny with Apache License 2.0 | 6 votes |
@Test public void testSubscribeWithItemFailureAndCompletion() { List<Long> items = new CopyOnWriteArrayList<>(); AtomicBoolean completion = new AtomicBoolean(); AtomicReference<Throwable> failure = new AtomicReference<>(); Multi.createFrom().ticks().every(Duration.ofMillis(10)) .transform().byTakingFirstItems(10) .subscribe().with(items::add, failure::set, () -> completion.set(true)); await().until(() -> items.size() > 5); await().until(completion::get); assertThat(items).contains(1L, 2L, 3L, 4L, 5L); assertThat(failure.get()).isNull(); assertThat(completion).isTrue(); }
Example #8
Source File: MultiBroadcastTest.java From smallrye-mutiny with Apache License 2.0 | 6 votes |
@Test public void testCancellationWithAtLeastAfterLastDeparture() { AtomicBoolean cancelled = new AtomicBoolean(); MultiEmitterProcessor<Integer> processor = MultiEmitterProcessor.create(); processor.onTermination(() -> cancelled.set(true)); Multi<Integer> multi = processor.toMulti().broadcast().withCancellationAfterLastSubscriberDeparture() .toAtLeast(2); MultiAssertSubscriber<Integer> s1 = multi.subscribe().withSubscriber(MultiAssertSubscriber.create(10)); s1.assertHasNotReceivedAnyItem().assertNotTerminated(); processor.emit(1).emit(2).emit(3); s1.assertHasNotReceivedAnyItem().assertNotTerminated(); MultiAssertSubscriber<Integer> s2 = multi.subscribe().withSubscriber(MultiAssertSubscriber.create(10)); s1.assertReceived(1, 2, 3).assertNotTerminated(); s2.assertReceived(1, 2, 3).assertNotTerminated(); s2.cancel(); assertThat(cancelled).isFalse(); s1.cancel(); assertThat(cancelled).isTrue(); }
Example #9
Source File: MultiSubscribeTest.java From smallrye-mutiny with Apache License 2.0 | 6 votes |
@Test public void testWithEmitterWithCompletion() { List<Integer> items = new CopyOnWriteArrayList<>(); AtomicBoolean completion = new AtomicBoolean(); AtomicReference<Throwable> failure = new AtomicReference<>(); AtomicReference<MultiEmitter<? super Integer>> emitter = new AtomicReference<>(); Multi.createFrom().<Integer> emitter(emitter::set) .subscribe().with(items::add, failure::set, () -> completion.set(true)); assertThat(items).isEmpty(); assertThat(failure.get()).isNull(); assertThat(completion).isFalse(); emitter.get().emit(1).emit(2).emit(3).complete(); assertThat(items).containsExactly(1, 2, 3); assertThat(failure.get()).isNull(); assertThat(completion).isTrue(); }
Example #10
Source File: UniOnNotNullItemTest.java From smallrye-mutiny with Apache License 2.0 | 6 votes |
@Test public void testProduceMulti() { assertThat(Uni.createFrom().item("hello") .onItem().ifNotNull().produceMulti(x -> Multi.createFrom().item(x.toUpperCase())) .collectItems().first() .await().indefinitely()).isEqualTo("HELLO"); assertThat(Uni.createFrom().item(() -> (String) null) .onItem().ifNotNull().produceMulti(x -> Multi.createFrom().item(x.toUpperCase())) .collectItems().first() .onItem().ifNull().continueWith("yolo") .await().indefinitely()).isEqualTo("yolo"); assertThatThrownBy(() -> Uni.createFrom().<String> failure(new Exception("boom")) .onItem().ifNotNull().produceMulti(x -> Multi.createFrom().item(x.toUpperCase())) .collectItems().first() .onItem().ifNull().continueWith("yolo") .await().indefinitely()).hasMessageContaining("boom"); }
Example #11
Source File: MultiToHotStreamTest.java From smallrye-mutiny with Apache License 2.0 | 6 votes |
@Test public void testWhenSubscriberDoesNotHaveRequestedEnough() { BroadcastProcessor<Integer> processor = BroadcastProcessor.create(); Multi<Integer> multi = processor.map(s -> s).transform().toHotStream(); MultiAssertSubscriber<Integer> s1 = multi.subscribe() .withSubscriber(MultiAssertSubscriber.create(10)); MultiAssertSubscriber<Integer> s2 = multi.subscribe() .withSubscriber(MultiAssertSubscriber.create(4)); for (int i = 0; i < 10; i++) { processor.onNext(i); } processor.onComplete(); s1.assertCompletedSuccessfully() .assertReceived(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); s2.assertHasFailedWith(BackPressureFailure.class, "request"); }
Example #12
Source File: MultiCombineTest.java From smallrye-mutiny with Apache License 2.0 | 6 votes |
@Test public void testCombinationOfNineStreamsAsTuple() { Multi<Integer> s1 = Multi.createFrom().range(1, 4); Multi<Integer> s2 = Multi.createFrom().range(2, 5); Multi<Integer> s3 = Multi.createFrom().range(3, 6); Multi<Integer> s4 = Multi.createFrom().range(4, 7); Multi<Integer> s5 = Multi.createFrom().range(5, 8); Multi<Integer> s6 = Multi.createFrom().range(6, 9); Multi<Integer> s7 = Multi.createFrom().range(7, 10); Multi<Integer> s8 = Multi.createFrom().range(8, 11); Multi<Integer> s9 = Multi.createFrom().range(9, 12); List<Tuple9<Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer>> list = Multi.createBy() .combining().streams(s1, s2, s3, s4, s5, s6, s7, s8, s9).asTuple() .collectItems().asList().await().indefinitely(); assertThat(list).hasSize(3) .containsExactly( Tuple9.of(1, 2, 3, 4, 5, 6, 7, 8, 9), Tuple9.of(2, 3, 4, 5, 6, 7, 8, 9, 10), Tuple9.of(3, 4, 5, 6, 7, 8, 9, 10, 11)); }
Example #13
Source File: KafkaPriceMessageProducer.java From smallrye-reactive-messaging with Apache License 2.0 | 5 votes |
@Outgoing("prices-out") public Multi<Message<Double>> generate() { // Build an infinite stream of random prices // It emits a price every second return Multi.createFrom().ticks().every(Duration.ofSeconds(1)) .map(x -> Message.of(random.nextDouble())); }
Example #14
Source File: MultiFlatten.java From smallrye-mutiny with Apache License 2.0 | 5 votes |
MultiFlatten(Multi<I> upstream, Function<? super I, ? extends Publisher<? extends O>> mapper, int requests, boolean collectFailures) { this.upstream = upstream; this.mapper = mapper; this.requests = requests; this.collectFailureUntilCompletion = collectFailures; }
Example #15
Source File: CamelPriceMessageProducer.java From smallrye-reactive-messaging with Apache License 2.0 | 5 votes |
@Outgoing("prices") public Multi<Message<String>> generate() { // Build an infinite stream of random prices return Multi.createFrom().ticks().every(Duration.ofSeconds(1)) .map(x -> random.nextDouble()) .map(p -> Double.toString(p)) .map(Message::of); }
Example #16
Source File: MultiOnFailureTest.java From smallrye-mutiny with Apache License 2.0 | 5 votes |
@Test public void testWhenRecoverWithMultiReturnsNull() { MultiAssertSubscriber<Integer> subscriber = MultiAssertSubscriber.create(0); Multi.createFrom().<Integer> failure(new IOException("karambar")) .onFailure().recoverWithMulti(v -> null) .subscribe().withSubscriber(subscriber); subscriber.assertHasNotReceivedAnyItem() .assertTerminated() .assertHasFailedWith(NullPointerException.class, "mapper"); }
Example #17
Source File: MultiConvertFromTest.java From smallrye-mutiny with Apache License 2.0 | 5 votes |
@Test public void testCreatingFromCompletionStageWithEmpty() { CompletableFuture<Void> empty = CompletableFuture.completedFuture(null); MultiAssertSubscriber<Void> subscriber = Multi.createFrom() .converter(BuiltinConverters.fromCompletionStage(), empty) .subscribe() .withSubscriber(MultiAssertSubscriber.create(1)); Multi.createFrom().completionStage(empty); subscriber.assertCompletedSuccessfully().assertHasNotReceivedAnyItem(); }
Example #18
Source File: ProcessorMediator.java From smallrye-reactive-messaging with Apache License 2.0 | 5 votes |
private Publisher<? extends Message<Object>> handleSkip(Message<Object> m) { if (m == null) { // If message is null, skip. return Multi.createFrom().empty(); } else { return Multi.createFrom().item(m); } }
Example #19
Source File: MultiConcatTckTest.java From smallrye-mutiny with Apache License 2.0 | 5 votes |
@Test public void concatStageShouldWorkWithEmptySecondGraph() { assertEquals(await( Multi.createBy().concatenating().streams( Multi.createFrom().items(1, 2, 3), Multi.createFrom().empty()) .collectItems().asList() .subscribeAsCompletionStage()), Arrays.asList(1, 2, 3)); }
Example #20
Source File: BeanWithProcessorsManipulatingMessages.java From smallrye-reactive-messaging with Apache License 2.0 | 5 votes |
@Outgoing(NO_ACKNOWLEDGMENT_CS) public Publisher<Message<String>> sourceToNoAckCS() { return Multi.createFrom().items("a", "b", "c", "d", "e") .map(payload -> Message.of(payload, () -> { nap(); acknowledged(NO_ACKNOWLEDGMENT_CS, payload); return CompletableFuture.completedFuture(null); })); }
Example #21
Source File: UniToMultiTest.java From smallrye-mutiny with Apache License 2.0 | 5 votes |
@Test public void testFromResult2() { AtomicInteger count = new AtomicInteger(); Multi<Integer> multi = Multi.createFrom().uni(Uni.createFrom().item(count::incrementAndGet)); multi.subscribe().withSubscriber(MultiAssertSubscriber.create(1)) .assertReceived(1) .assertCompletedSuccessfully(); multi.subscribe().withSubscriber(MultiAssertSubscriber.create(0)).assertNotTerminated() .assertHasNotReceivedAnyItem() .request(1) .assertReceived(2) .assertCompletedSuccessfully(); }
Example #22
Source File: MultiCreateFromDeferredSupplierTest.java From smallrye-mutiny with Apache License 2.0 | 5 votes |
@Test public void testThatEachSubscriberHasItsOwn() { AtomicInteger count = new AtomicInteger(); Multi<Integer> multi = Multi.createFrom().deferred(() -> Multi.createFrom().item(count.incrementAndGet())); MultiAssertSubscriber<Integer> s1 = multi.subscribe().withSubscriber(MultiAssertSubscriber.create(1)); MultiAssertSubscriber<Integer> s2 = multi.subscribe().withSubscriber(MultiAssertSubscriber.create(1)); MultiAssertSubscriber<Integer> s3 = multi.subscribe().withSubscriber(MultiAssertSubscriber.create(1)); s1.assertReceived(1).assertCompletedSuccessfully(); s2.assertReceived(2).assertCompletedSuccessfully(); s3.assertReceived(3).assertCompletedSuccessfully(); }
Example #23
Source File: MultiFlatMapTckTest.java From smallrye-mutiny with Apache License 2.0 | 5 votes |
@Test public void flatMapStageShouldMapElements() { assertEquals(await(Multi.createFrom().items(1, 2, 3) .emitOn(executor) .flatMap(n -> Multi.createFrom().items(n, n, n)) .collectItems().asList() .subscribeAsCompletionStage()), Arrays.asList(1, 1, 1, 2, 2, 2, 3, 3, 3)); }
Example #24
Source File: AckChainTest.java From smallrye-reactive-messaging with Apache License 2.0 | 5 votes |
@Outgoing("A") public Multi<Message<Integer>> generate() { return Multi.createFrom().range(0, 20) .map(i -> Message.of(i, () -> { acks.incrementAndGet(); return CompletableFuture.completedFuture(null); })); }
Example #25
Source File: JmsSource.java From smallrye-reactive-messaging with Apache License 2.0 | 5 votes |
JmsSource(JMSContext context, JmsConnectorIncomingConfiguration config, Jsonb json, Executor executor) { String name = config.getDestination().orElseGet(config::getChannel); String selector = config.getSelector().orElse(null); boolean nolocal = config.getNoLocal(); boolean broadcast = config.getBroadcast(); boolean durable = config.getDurable(); Destination destination = getDestination(context, name, config); JMSConsumer consumer; if (durable) { if (!(destination instanceof Topic)) { throw ex.illegalArgumentInvalidDestination(); } consumer = context.createDurableConsumer((Topic) destination, name, selector, nolocal); } else { consumer = context.createConsumer(destination, selector, nolocal); } publisher = new JmsPublisher(consumer); if (!broadcast) { source = ReactiveStreams.fromPublisher(publisher).map(m -> new IncomingJmsMessage<>(m, executor, json)); } else { source = ReactiveStreams.fromPublisher( Multi.createFrom().publisher(publisher) .map(m -> new IncomingJmsMessage<>(m, executor, json)) .broadcast().toAllSubscribers()); } }
Example #26
Source File: MultiFlatMapToPublisherTest.java From smallrye-mutiny with Apache License 2.0 | 5 votes |
@Test public void testThatFlatMapIsNotCalledOnUpstreamFailure() { MultiAssertSubscriber<Integer> subscriber = MultiAssertSubscriber.create(Long.MAX_VALUE); AtomicInteger count = new AtomicInteger(); Multi.createFrom().<Integer> failure(new IOException("boom")) .flatMap(i -> { count.incrementAndGet(); return Multi.createFrom().item(i); }) .subscribe(subscriber); subscriber.assertHasFailedWith(IOException.class, "boom"); assertThat(count).hasValue(0); }
Example #27
Source File: MessageProcessorAckTest.java From smallrye-reactive-messaging with Apache License 2.0 | 5 votes |
private List<Throwable> run(Set<String> acked, Set<String> nacked, Emitter<String> emitter) throws InterruptedException { List<Throwable> reasons = new CopyOnWriteArrayList<>(); CountDownLatch done = new CountDownLatch(1); Multi.createFrom().items("a", "b", "c", "d", "e", "f", "g", "h", "i", "j") .onItem() .produceCompletionStage(i -> CompletableFuture.runAsync(() -> emitter.send(Message.of(i, Metadata.empty(), () -> { acked.add(i); return CompletableFuture.completedFuture(null); }, t -> { reasons.add(t); nacked.add(i); return CompletableFuture.completedFuture(null); }))) .thenApply(x -> i)) .merge() .subscribe().with( x -> { // noop }, f -> { // noop }, done::countDown); done.await(10, TimeUnit.SECONDS); return reasons; }
Example #28
Source File: StreamSkip.java From smallrye-reactive-messaging with Apache License 2.0 | 5 votes |
@Incoming("in") @Outgoing("out-3") public Multi<String> processPayloadStream(Multi<String> stream) { return stream .transform().byFilteringItemsWith(s -> !s.equalsIgnoreCase("skip")) .onItem().apply(String::toUpperCase); }
Example #29
Source File: BeanWithPayloadProcessors.java From smallrye-reactive-messaging with Apache License 2.0 | 5 votes |
@Outgoing(DEFAULT_ACKNOWLEDGMENT) public Publisher<Message<String>> sourceToAutoAck() { return Multi.createFrom().items("a", "b", "c", "d", "e") .map(payload -> Message.of(payload, () -> { nap(); acknowledged(DEFAULT_ACKNOWLEDGMENT, payload); return CompletableFuture.completedFuture(null); })); }
Example #30
Source File: BeanWithPayloadProcessors.java From smallrye-reactive-messaging with Apache License 2.0 | 5 votes |
@Outgoing(PRE_ACKNOWLEDGMENT_BUILDER) public Publisher<Message<String>> sourceToPreAckWithBuilder() { return Multi.createFrom().items("a", "b", "c", "d", "e") .map(payload -> Message.of(payload, () -> { nap(); acknowledged(PRE_ACKNOWLEDGMENT_BUILDER, payload); return CompletableFuture.completedFuture(null); })); }