org.reactivestreams.Subscriber Java Examples

The following examples show how to use org.reactivestreams.Subscriber. 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: FlowableToFutureTest.java    From RxJava3-preview with Apache License 2.0 7 votes vote down vote up
@Test
public void testSuccess() throws Exception {
    @SuppressWarnings("unchecked")
    Future<Object> future = mock(Future.class);
    Object value = new Object();
    when(future.get()).thenReturn(value);

    Subscriber<Object> o = TestHelper.mockSubscriber();

    TestSubscriber<Object> ts = new TestSubscriber<Object>(o);

    Flowable.fromFuture(future).subscribe(ts);

    ts.dispose();

    verify(o, times(1)).onNext(value);
    verify(o, times(1)).onComplete();
    verify(o, never()).onError(any(Throwable.class));
    verify(future, never()).cancel(anyBoolean());
}
 
Example #2
Source File: FlowableZipIterableTest.java    From RxJava3-preview with Apache License 2.0 6 votes vote down vote up
@Test
public void testZipIterableSameSize() {
    PublishProcessor<String> r1 = PublishProcessor.create();
    /* define a Subscriber to receive aggregated events */
    Subscriber<String> o = TestHelper.mockSubscriber();
    InOrder io = inOrder(o);

    Iterable<String> r2 = Arrays.asList("1", "2", "3");

    r1.zipWith(r2, zipr2).subscribe(o);

    r1.onNext("one-");
    r1.onNext("two-");
    r1.onNext("three-");
    r1.onComplete();

    io.verify(o).onNext("one-1");
    io.verify(o).onNext("two-2");
    io.verify(o).onNext("three-3");
    io.verify(o).onComplete();

    verify(o, never()).onError(any(Throwable.class));

}
 
Example #3
Source File: ParallelFlowableLife.java    From rxjava-RxLife with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public void subscribe(@NonNull Subscriber<? super T>[] subscribers) {
    if (!validate(subscribers)) {
        return;
    }

    int n = subscribers.length;

    Subscriber<? super T>[] parents = new Subscriber[n];

    for (int i = 0; i < n; i++) {
        Subscriber<? super T> a = subscribers[i];
        if (a instanceof ConditionalSubscriber) {
            parents[i] = new LifeConditionalSubscriber<>((ConditionalSubscriber<? super T>) a, scope);
        } else {
            parents[i] = new LifeSubscriber<>(a, scope);
        }
    }
    ParallelFlowable<T> upStream = this.upStream;
    if (onMain) upStream = upStream.runOn(AndroidSchedulers.mainThread());
    upStream.subscribe(parents);
}
 
Example #4
Source File: ScheduledPublisher.java    From smallrye-mutiny with Apache License 2.0 6 votes vote down vote up
@Override
public void subscribe(Subscriber<? super Integer> subscriber) {
    assertEquals(activePublishers.incrementAndGet(), 1);
    subscriber.onSubscribe(new Subscription() {
        @Override
        public void request(long n) {
            if (published.compareAndSet(false, true)) {
                getExecutorService().schedule(() -> {
                    subscriber.onNext(id);
                    getExecutorService().schedule(() -> {
                        activePublishers.decrementAndGet();
                        subscriber.onComplete();
                    }, 100, TimeUnit.MILLISECONDS);
                }, 100, TimeUnit.MILLISECONDS);
            }
        }

        @Override
        public void cancel() {
        }
    });
}
 
Example #5
Source File: MultiMapOnFailure.java    From smallrye-mutiny with Apache License 2.0 6 votes vote down vote up
@Override
public void subscribe(Subscriber<? super T> subscriber) {
    if (subscriber == null) {
        throw new NullPointerException("The subscriber must not be `null`");
    }
    Function<? super Throwable, ? extends Publisher<? extends T>> next = failure -> {
        if (predicate.test(failure)) {
            Throwable throwable = mapper.apply(failure);
            if (throwable == null) {
                return Multi.createFrom().failure(new NullPointerException(MAPPER_RETURNED_NULL));
            } else {
                return Multi.createFrom().failure(throwable);
            }
        }
        return Multi.createFrom().failure(failure);
    };
    Multi<T> op = Infrastructure.onMultiCreation(new MultiOnFailureResumeOp<>(upstream(), next));
    op.subscribe(subscriber);
}
 
Example #6
Source File: AsyncProcessorTest.java    From RxJava3-preview with Apache License 2.0 6 votes vote down vote up
@Test
public void testSubscribeAfterCompleted() {
    AsyncProcessor<String> subject = AsyncProcessor.create();

    Subscriber<String> observer = TestHelper.mockSubscriber();

    subject.onNext("one");
    subject.onNext("two");
    subject.onNext("three");
    subject.onComplete();

    subject.subscribe(observer);

    verify(observer, times(1)).onNext("three");
    verify(observer, Mockito.never()).onError(any(Throwable.class));
    verify(observer, times(1)).onComplete();
}
 
Example #7
Source File: RxBusBuilder.java    From RxBus2 with Apache License 2.0 6 votes vote down vote up
public <R> Disposable subscribe(DisposableSubscriber<R> subscriber, FlowableTransformer<T, R> transformer)
{
    Flowable flowable = build(false);
    if (transformer != null)
        flowable = flowable.compose(transformer);

    Subscriber<R> actualSubscriber = subscriber;
    if (mQueuer != null && mQueueSubscriptionSafetyCheckEnabled)
        actualSubscriber = RxBusUtil.wrapSubscriber(subscriber, mQueuer);

    flowable = applySchedular(flowable);
    Disposable disposable = (DisposableSubscriber)flowable.subscribeWith(actualSubscriber);
    if (mBoundObject != null)
        RxDisposableManager.addDisposable(mBoundObject, disposable);
    return disposable;
}
 
Example #8
Source File: AppendOnlyLinkedArrayList.java    From RxJava3-preview with Apache License 2.0 6 votes vote down vote up
/**
 * Interprets the contents as NotificationLite objects and calls
 * the appropriate Subscriber method.
 * 
 * @param <U> the target type
 * @param subscriber the subscriber to emit the events to
 * @return true if a terminal event has been reached
 */
public <U> boolean accept(Subscriber<? super U> subscriber) {
    Object[] a = head;
    final int c = capacity;
    while (a != null) {
        for (int i = 0; i < c; i++) {
            Object o = a[i];
            if (o == null) {
                break;
            }

            if (NotificationLite.acceptFull(o, subscriber)) {
                return true;
            }
        }
        a = (Object[])a[c];
    }
    return false;
}
 
Example #9
Source File: VertxClientHttpRequest.java    From vertx-spring-boot with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<Void> writeWith(Publisher<? extends DataBuffer> chunks) {
    Mono<Void> writeCompletion = Mono.create(sink -> {
        logger.debug("Subscribing to body publisher");
        Subscriber<DataBuffer> subscriber = new WriteStreamSubscriber.Builder<HttpClientRequest, DataBuffer>()
            .writeStream(delegate)
            .endHook(sink)
            .nextHandler((stream, value) -> stream.write(bufferConverter.toBuffer(value)))
            .build();
        chunks.subscribe(subscriber);
    });

    Mono<Void> endCompletion = Mono.create(sink -> {
        logger.debug("Completing request after writing");
        delegate.end();
        sink.success();
    });

    return doCommit(() -> writeCompletion.then(endCompletion));
}
 
Example #10
Source File: PublisherSignatureTest.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("SubscriberImplementation")
@Incoming("G")
public Subscriber<Integer> consume() {
    return new Subscriber<Integer>() {
        @Override
        public void onSubscribe(Subscription subscription) {
            subscription.request(10);
        }

        @Override
        public void onNext(Integer integer) {
            getItems().add(integer);
        }

        @Override
        public void onError(Throwable throwable) {
            // Ignored
        }

        @Override
        public void onComplete() {
            // Ignored
        }
    };
}
 
Example #11
Source File: EventBusSinkTest.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testSinkUsingString() {
    String topic = UUID.randomUUID().toString();
    AtomicInteger expected = new AtomicInteger(0);
    usage.consumeStrings(topic, 10, 10, TimeUnit.SECONDS,
            v -> expected.getAndIncrement());

    Map<String, Object> config = new HashMap<>();
    config.put("address", topic);
    EventBusSink sink = new EventBusSink(vertx,
            new VertxEventBusConnectorOutgoingConfiguration(new MapBasedConfig(config)));

    SubscriberBuilder<? extends Message<?>, Void> subscriber = sink.sink();
    Multi.createFrom().range(0, 10)
            .map(i -> Integer.toString(i))
            .map(Message::of)
            .subscribe((Subscriber<Message<?>>) subscriber.build());
    await().untilAtomic(expected, is(10));
    assertThat(expected).hasValue(10);
}
 
Example #12
Source File: TestEmployeeBatchStream.java    From Spring-5.0-Cookbook with MIT License 6 votes vote down vote up
@Test
public void testTimedFirstNames(){
	employeeBatchStreamServiceImpl.getTimedFirstNames().subscribe(new Subscriber<String>(){

		@Override
		public void onComplete() {	}

		@Override
		public void onError(Throwable arg0) {
			System.out.println("time is out....");
		}

		@Override
		public void onNext(String data) {
			System.out.println(data);
		}

		@Override
		public void onSubscribe(Subscription subs) {
			subs.request(Long.MAX_VALUE);
		}
		
	});
}
 
Example #13
Source File: AmqpCreditBasedSender.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
@Override
public void onNext(Message<?> message) {
    if (isCancelled()) {
        return;
    }

    Subscriber<? super Message<?>> subscriber = this.downstream.get();
    send(sender, message, durable, ttl, configuredAddress, useAnonymousSender, configuration)
            .subscribe().with(
                    res -> {
                        subscriber.onNext(res);
                        if (requested.decrementAndGet() == 0) { // no more credit, request more
                            onNoMoreCredit();
                        }
                    },
                    subscriber::onError);
}
 
Example #14
Source File: NettyByteStream.java    From styx with Apache License 2.0 6 votes vote down vote up
@Override
public void subscribe(Subscriber<? super Buffer> subscriber) {
    ByteBufToBufferSubscriber byteBufToBufferSubscriber = new ByteBufToBufferSubscriber(subscriber);
    eventLoop.submit(() -> contentProducer.onSubscribed(byteBufToBufferSubscriber));
    byteBufToBufferSubscriber.onSubscribe(new Subscription() {
        @Override
        public void request(long n) {
            eventLoop.submit(() -> contentProducer.request(n));
        }

        @Override
        public void cancel() {
            eventLoop.submit(contentProducer::unsubscribe);
        }
    });
}
 
Example #15
Source File: AbstractStreamObserverAndPublisher.java    From reactive-grpc with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private boolean checkTerminated(boolean d, boolean empty, Subscriber<? super T> subscriber, Queue<T> q) {
    if (cancelled) {
        q.clear();
        downstream = null;
        return true;
    }

    if (d && empty) {
        Throwable e = error;
        downstream = null;
        if (e != null) {
            subscriber.onError(e);
        } else {
            subscriber.onComplete();
        }
        return true;
    }

    return false;
}
 
Example #16
Source File: FlowableTakeUntilPredicateTest.java    From RxJava3-preview with Apache License 2.0 6 votes vote down vote up
@Test
public void takeAll() {
    Subscriber<Object> o = TestHelper.mockSubscriber();

    Flowable.just(1, 2).takeUntil(new Predicate<Integer>() {
        @Override
        public boolean test(Integer v) {
            return false;
        }
    }).subscribe(o);

    verify(o).onNext(1);
    verify(o).onNext(2);
    verify(o, never()).onError(any(Throwable.class));
    verify(o).onComplete();
}
 
Example #17
Source File: FlowableToFutureTest.java    From RxJava3-preview with Apache License 2.0 6 votes vote down vote up
@Test
public void testCancelledBeforeSubscribe() throws Exception {
    @SuppressWarnings("unchecked")
    Future<Object> future = mock(Future.class);
    CancellationException e = new CancellationException("unit test synthetic cancellation");
    when(future.get()).thenThrow(e);

    Subscriber<Object> o = TestHelper.mockSubscriber();

    TestSubscriber<Object> ts = new TestSubscriber<Object>(o);
    ts.dispose();

    Flowable.fromFuture(future).subscribe(ts);

    ts.assertNoErrors();
    ts.assertNotComplete();
}
 
Example #18
Source File: ParallelJoinTest.java    From RxJava3-preview with Apache License 2.0 6 votes vote down vote up
@Test
public void overflowFastpathDelayError() {
    new ParallelFlowable<Integer>() {
        @Override
        public void subscribe(Subscriber<? super Integer>[] subscribers) {
            subscribers[0].onSubscribe(new BooleanSubscription());
            subscribers[0].onNext(1);
            subscribers[0].onNext(2);
        }

        @Override
        public int parallelism() {
            return 1;
        }
    }
    .sequentialDelayError(1)
    .test(0)
    .requestMore(1)
    .assertFailure(MissingBackpressureException.class, 1);
}
 
Example #19
Source File: QueueDrainSubscriber.java    From RxJava3-preview with Apache License 2.0 5 votes vote down vote up
protected final void fastPathOrderedEmitMax(U value, boolean delayError, Disposable dispose) {
    final Subscriber<? super V> s = actual;
    final SimplePlainQueue<U> q = queue;

    if (wip.get() == 0 && wip.compareAndSet(0, 1)) {
        long r = requested.get();
        if (r != 0L) {
            if (q.isEmpty()) {
                if (accept(s, value)) {
                    if (r != Long.MAX_VALUE) {
                        produced(1);
                    }
                }
                if (leave(-1) == 0) {
                    return;
                }
            } else {
                q.offer(value);
            }
        } else {
            cancelled = true;
            dispose.dispose();
            s.onError(new MissingBackpressureException("Could not emit buffer due to lack of requests"));
            return;
        }
    } else {
        q.offer(value);
        if (!enter()) {
            return;
        }
    }
    QueueDrainHelper.drainMaxLoop(q, s, delayError, dispose, this);
}
 
Example #20
Source File: APITest.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@Test
public void testBuildingPublisherFromSpec() {
    List<MyDomainObject> domainObjects = Arrays.asList(new MyDomainObject("Clement", "Neo"),
            new MyDomainObject("Tintin", "Milou"));

    Publisher<ByteBuffer> publisher = ReactiveStreams.fromIterable(domainObjects)
            .map(obj -> String.format("%s,%s\n", obj.field1, obj.field2))
            .map(line -> ByteBuffer.wrap(line.getBytes()))
            .buildRs();

    List<String> list = new ArrayList<>();
    AtomicBoolean done = new AtomicBoolean();

    executor.submit(() -> publisher.subscribe(new Subscriber<ByteBuffer>() {
        @Override
        public void onSubscribe(Subscription s) {
            s.request(5);
        }

        @Override
        public void onNext(ByteBuffer byteBuffer) {
            list.add(new String(byteBuffer.array()));
        }

        @Override
        public void onError(Throwable t) {

        }

        @Override
        public void onComplete() {
            done.set(true);
        }
    }));

    await().untilAtomic(done, is(true));
    assertThat(list).containsExactly("Clement,Neo\n", "Tintin,Milou\n");
}
 
Example #21
Source File: UniRepeatTest.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@Test
public void testFailurePropagation() {
    Subscriber<Integer> subscriber = Mocks.subscriber();

    Uni.createFrom().<Integer> failure(() -> new IOException("boom")).repeat().indefinitely()
            .transform().byTakingFirstItems(10)
            .subscribe(subscriber);

    verify(subscriber).onError(any(IOException.class));
    verify(subscriber, never()).onComplete();
    verify(subscriber, never()).onNext(any());
}
 
Example #22
Source File: ArticalRemoteDataSource.java    From KotlinMVPRxJava2Dagger2GreenDaoRetrofitDemo with Apache License 2.0 5 votes vote down vote up
@Override
public void getMeiziData(@NonNull final GankCallback callback, int pageNum, int pageSize) {
    RetrofitManager.getInstance()
            .createGankApiService()
            .getDailyMeiziData("福利",pageSize,pageNum)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<GankEntity>() {
                @Override
                public void onSubscribe(Subscription s) {
                    s.request(Long.MAX_VALUE);
                }

                @Override
                public void onNext(GankEntity gankEntity) {
                    callback.onGankdataLoaded(gankEntity);
                }

                @Override
                public void onError(Throwable t) {
                    callback.onDataNotAvailable(t);
                }

                @Override
                public void onComplete() {

                }
            });
}
 
Example #23
Source File: FlowableAutoConnect.java    From RxJava3-preview with Apache License 2.0 5 votes vote down vote up
@Override
public void subscribeActual(Subscriber<? super T> child) {
    source.subscribe(child);
    if (clients.incrementAndGet() == numberOfSubscribers) {
        source.connect(connection);
    }
}
 
Example #24
Source File: FlowableSkipLastTimedTest.java    From RxJava3-preview with Apache License 2.0 5 votes vote down vote up
@Test
public void testSkipLastTimedWhenAllElementsAreValid() {
    TestScheduler scheduler = new TestScheduler();

    PublishProcessor<Integer> source = PublishProcessor.create();

    Flowable<Integer> result = source.skipLast(1, TimeUnit.MILLISECONDS, scheduler);

    Subscriber<Object> o = TestHelper.mockSubscriber();

    result.subscribe(o);

    source.onNext(1);
    source.onNext(2);
    source.onNext(3);

    scheduler.advanceTimeBy(500, TimeUnit.MILLISECONDS);

    source.onComplete();

    InOrder inOrder = inOrder(o);
    inOrder.verify(o).onNext(1);
    inOrder.verify(o).onNext(2);
    inOrder.verify(o).onNext(3);
    inOrder.verify(o).onComplete();
    inOrder.verifyNoMoreInteractions();
}
 
Example #25
Source File: SingleFromPublisherTest.java    From RxJava3-preview with Apache License 2.0 5 votes vote down vote up
@Test
public void badSource() {
    List<Throwable> errors = TestCommonHelper.trackPluginErrors();

    try {
        singleOrError(new Flowable<Integer>() {
            @Override
            protected void subscribeActual(Subscriber<? super Integer> s) {
                s.onSubscribe(new BooleanSubscription());
                BooleanSubscription s2 = new BooleanSubscription();
                s.onSubscribe(s2);
                assertTrue(s2.isCancelled());

                s.onNext(1);
                s.onComplete();
                s.onNext(2);
                s.onError(new TestException());
                s.onComplete();
            }
        })
        .test()
        .assertResult(1);

        TestCommonHelper.assertError(errors, 0, IllegalStateException.class, "Subscription already set!");
        TestCommonHelper.assertUndeliverable(errors, 1, TestException.class);
    } finally {
        RxJavaCommonPlugins.reset();
    }
}
 
Example #26
Source File: APITest.java    From smallrye-reactive-streams-operators with Apache License 2.0 5 votes vote down vote up
@Test
public void testBuildingPublisherFromSpec() {
    List<MyDomainObject> domainObjects = Arrays.asList(new MyDomainObject("Clement", "Neo"),
            new MyDomainObject("Tintin", "Milou"));

    Publisher<ByteBuffer> publisher = ReactiveStreams.fromIterable(domainObjects)
            .map(obj -> String.format("%s,%s\n", obj.field1, obj.field2))
            .map(line -> ByteBuffer.wrap(line.getBytes()))
            .buildRs();

    List<String> list = new ArrayList<>();
    AtomicBoolean done = new AtomicBoolean();

    executor.submit(() -> publisher.subscribe(new Subscriber<ByteBuffer>() {
        @Override
        public void onSubscribe(Subscription s) {
            s.request(5);
        }

        @Override
        public void onNext(ByteBuffer byteBuffer) {
            list.add(new String(byteBuffer.array()));
        }

        @Override
        public void onError(Throwable t) {

        }

        @Override
        public void onComplete() {
            done.set(true);
        }
    }));

    await().untilAtomic(done, is(true));
    assertThat(list).containsExactly("Clement,Neo\n", "Tintin,Milou\n");
}
 
Example #27
Source File: EventBusSinkTest.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testExpectReply() {
    String topic = UUID.randomUUID().toString();

    List<Integer> integers = new ArrayList<>();
    AtomicReference<io.vertx.mutiny.core.eventbus.Message<Integer>> last = new AtomicReference<>();
    vertx.eventBus().<Integer> consumer(topic, m -> {
        last.set(m);
        if (m.body() < 8) {
            integers.add(m.body());
            m.replyAndForget("foo");
        }
    });

    Map<String, Object> config = new HashMap<>();
    config.put("address", topic);
    config.put("expect-reply", true);
    EventBusSink sink = new EventBusSink(vertx,
            new VertxEventBusConnectorOutgoingConfiguration(new MapBasedConfig(config)));

    SubscriberBuilder<? extends Message<?>, Void> subscriber = sink.sink();
    Multi.createFrom().range(0, 10)
            .map(Message::of)
            .subscribe((Subscriber<Message<?>>) subscriber.build());

    await().until(() -> integers.size() == 8 && last.get().body() == 8);
    last.get().replyAndForget("bar");
    await().until(() -> last.get().body() == 9);
    assertThat(last.get().body()).isEqualTo(9);
    last.get().replyAndForget("baz");
}
 
Example #28
Source File: ChecksumValidatingPublisher.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
ChecksumValidatingSubscriber(Subscriber<? super ByteBuffer> wrapped,
                             SdkChecksum sdkChecksum,
                             long contentLength) {
    this.wrapped = wrapped;
    this.sdkChecksum = sdkChecksum;
    this.strippedLength = contentLength - CHECKSUM_SIZE;
}
 
Example #29
Source File: SafeSubscriberTest.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@Test
public void testThatOnNextWithoutSubscriptionIsAProtocolViolation() {
    Subscriber<String> subscriber = mock(Subscriber.class);

    SafeSubscriber<String> safe = new SafeSubscriber<>(subscriber);

    safe.onNext("hello");
    verify(subscriber, times(0)).onNext("hello");
    verify(subscriber, times(1)).onSubscribe(any(Subscriptions.EmptySubscription.class));
    verify(subscriber, times(1)).onError(any(NullPointerException.class));
}
 
Example #30
Source File: FlowableRange.java    From RxJava3-preview with Apache License 2.0 5 votes vote down vote up
@Override
public void subscribeActual(Subscriber<? super Integer> s) {
    if (s instanceof ConditionalSubscriber) {
        s.onSubscribe(new RangeConditionalSubscription(
                (ConditionalSubscriber<? super Integer>)s, start, end));
    } else {
        s.onSubscribe(new RangeSubscription(s, start, end));
    }
}