Java Code Examples for io.smallrye.mutiny.Multi

The following examples show how to use io.smallrye.mutiny.Multi. 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
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 Project: quarkus   Source File: ReflectionService.java    License: Apache License 2.0 6 votes vote down vote up
@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 Project: smallrye-mutiny   Source File: MultiBroadcastTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 4
Source Project: smallrye-reactive-messaging   Source File: AmqpSinkTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 5
Source Project: smallrye-mutiny   Source File: MultiFlattenTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 6
Source Project: smallrye-mutiny   Source File: MultiToHotStreamTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 7
Source Project: smallrye-mutiny   Source File: MultiCombineTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 8
Source Project: smallrye-mutiny   Source File: UniOnNotNullItemTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 9
Source Project: smallrye-mutiny   Source File: MultiRepetitionTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 10
Source Project: quarkus   Source File: ServerCalls.java    License: Apache License 2.0 6 votes vote down vote up
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 11
Source Project: smallrye-mutiny   Source File: MultiSubscribeTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 12
Source Project: smallrye-mutiny   Source File: MultiSubscribeTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 13
Source Project: smallrye-mutiny   Source File: MultiOnFailureTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testRecoverWithCompletion() {
    Multi.createFrom().<Integer> failure(new IllegalStateException("boom"))
            .onFailure().recoverWithCompletion()
            .subscribe().withSubscriber(MultiAssertSubscriber.create(1))
            .assertCompletedSuccessfully()
            .assertHasNotReceivedAnyItem();
}
 
Example 14
Source Project: smallrye-mutiny   Source File: MultiDistinctTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testDistinctOnAStreamWithoutDuplicates() {
    Multi.createFrom().range(1, 5)
            .transform().byDroppingDuplicates()
            .subscribe().withSubscriber(MultiAssertSubscriber.create(10))
            .assertCompletedSuccessfully()
            .assertReceived(1, 2, 3, 4);
}
 
Example 15
Source Project: smallrye-mutiny   Source File: MultiWindowOnDurationOp.java    License: Apache License 2.0 5 votes vote down vote up
WindowTimeoutSubscriber(MultiSubscriber<? super Multi<T>> downstream, Duration duration,
        ScheduledExecutorService scheduler) {
    super(downstream);
    this.queue = new MpscLinkedQueue<>();
    this.duration = duration;
    this.scheduler = scheduler;
}
 
Example 16
Source Project: smallrye-mutiny   Source File: CollectTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void collect() {
    Multi<Integer> multi = Multi.createFrom().range(1, 3);
    // tag::code[]

    // collectItems let you collect items into a Uni of data structure.
    // The final result is emitted when the completion event is received
    Uni<List<Integer>> list = multi.collectItems().asList();
    Uni<Map<String, Integer>> map = multi.collectItems().asMap(i -> Integer.toString(i));

    // You can retrieve the first and last items
    Uni<Integer> first = multi.collectItems().first();
    Uni<Integer> last = multi.collectItems().last();

    // you can also get a **blocking** iterable / streams
    BlockingIterable<Integer> integers = multi.subscribe().asIterable();
    Stream<Integer> stream = multi.subscribe().asStream();

    // end::code[]

    assertThat(list.await().indefinitely()).containsExactly(1, 2);
    assertThat(map.await().indefinitely()).hasSize(2).containsKeys("1", "2");
    assertThat(first.await().indefinitely()).isEqualTo(1);
    assertThat(last.await().indefinitely()).isEqualTo(2);
    assertThat(integers).containsExactly(1, 2);
    assertThat(stream).containsExactly(1, 2);
}
 
Example 17
Source Project: smallrye-mutiny   Source File: MultiConvertFromTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCreatingFromCompletionStageWithValue() {
    CompletableFuture<Integer> valued = CompletableFuture.completedFuture(1);

    MultiAssertSubscriber<Integer> subscriber = Multi.createFrom()
            .completionStage(valued)
            .subscribe()
            .withSubscriber(MultiAssertSubscriber.create(1));

    subscriber.assertCompletedSuccessfully().assertReceived(1);
}
 
Example 18
Source Project: smallrye-mutiny   Source File: MultiConvertToTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCreatingAMaybeFromNull() {
    Maybe<Integer> maybe = Multi.createFrom().item((Integer) null).convert().with(MultiRxConverters.toMaybe());
    assertThat(maybe).isNotNull();
    maybe
            .test()
            .assertComplete()
            .assertNoValues();
}
 
Example 19
Source Project: smallrye-mutiny   Source File: MultiOnFailureTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testRequestOnTheMultiReturnedByRecoverWithMulti() {
    MultiAssertSubscriber<Integer> subscriber = MultiAssertSubscriber.create(0);

    Multi.createFrom()
            .<Integer> failure(new IllegalStateException("boom"))
            .onFailure().recoverWithMulti(v -> Multi.createFrom().range(50, 61))
            .subscribe().withSubscriber(subscriber);

    subscriber.assertHasNotReceivedAnyItem()
            .assertHasNotFailed()
            .assertNotTerminated();

    subscriber.request(4)
            .assertReceived(50, 51, 52, 53)
            .assertHasNotFailed()
            .assertNotTerminated();

    subscriber.request(5)
            .assertReceived(50, 51, 52, 53, 54, 55, 56, 57, 58)
            .assertHasNotFailed()
            .assertNotTerminated();

    subscriber.request(5)
            .assertReceived(50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60)
            .assertHasNotFailed()
            .assertCompletedSuccessfully();
}
 
Example 20
@Outgoing(NO_ACKNOWLEDGMENT_BUILDER)
public Publisher<Message<String>> sourceToNoAckWithBuilder() {
    return Multi.createFrom().items("a", "b", "c", "d", "e")
            .map(payload -> Message.of(payload, () -> {
                nap();
                acknowledged(NO_ACKNOWLEDGMENT_BUILDER, payload);
                return CompletableFuture.completedFuture(null);
            }));
}
 
Example 21
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 22
@Incoming("in")
@Outgoing("out")
public Publisher<Message<String>> transform(Multi<Message<String>> stream) {
    return stream
        .map(message ->
            message.withPayload(message.getPayload().toUpperCase())
        );
}
 
Example 23
@Outgoing(PRE_ACKNOWLEDGMENT_BUILDER)
public Publisher<Message<String>> sourceToPreAckBuilder() {
    return Multi.createFrom().items("a", "b", "c", "d", "e")
            .map(payload -> Message.of(payload, () -> {
                nap();
                acknowledged(PRE_ACKNOWLEDGMENT_BUILDER, payload);
                return CompletableFuture.completedFuture(null);
            }));
}
 
Example 24
@Override
public Publisher<Long> createFailedPublisher() {
    return Multi.createFrom().<Long> failure(new RuntimeException("failed"))
            .onFailure().recoverWithItem(t -> {
                // Re-throw the exception.
                if (t instanceof RuntimeException) {
                    throw (RuntimeException) t;
                }
                // Wrap if required.
                throw new RuntimeException(t);
            });
}
 
Example 25
Source Project: smallrye-mutiny   Source File: MultiConvertFromTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCreatingFromAMultiValuedObservable() {
    MultiAssertSubscriber<Integer> subscriber = Multi.createFrom()
            .converter(MultiRxConverters.fromObservable(), Observable.just(1, 2, 3))
            .subscribe()
            .withSubscriber(MultiAssertSubscriber.create(3));

    subscriber.assertCompletedSuccessfully().assertReceived(1, 2, 3);
}
 
Example 26
@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);
            }));
}
 
Example 27
@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 28
Source Project: smallrye-reactive-messaging   Source File: StreamSkip.java    License: Apache License 2.0 5 votes vote down vote up
@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
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 30
@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);
}