org.reactivestreams.Subscription Java Examples

The following examples show how to use org.reactivestreams.Subscription. 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: SafeSubscriberTest.java    From smallrye-mutiny with Apache License 2.0 6 votes vote down vote up
@Test
public void testThatDownstreamFailuresAreHandledInOnError() {
    Subscriber<String> subscriber = mock(Subscriber.class);
    doAnswer(new ThrowsException(new IllegalStateException("boom"))).when(subscriber).onError(any());

    Subscription subscription = mock(Subscription.class);

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

    safe.onSubscribe(subscription);
    verify(subscriber, times(1)).onSubscribe(safe);

    Exception boom = new Exception("boom");
    safe.onError(boom);
    // called
    verify(subscriber, times(1)).onError(boom);
    assertThat(safe.isDone()).isTrue();
}
 
Example #2
Source File: SubscriberBarrier.java    From camunda-bpm-reactor with Apache License 2.0 6 votes vote down vote up
@Override
public final void onSubscribe(Subscription s) {
  if (s == null) {
    throw SpecificationExceptions.spec_2_13_exception();
  }

  try {
    if (subscription != null) {
      s.cancel();
      return;
    }
    subscription = s;
    doSubscribe(this);
  } catch (Throwable throwable) {
    Exceptions.throwIfFatal(throwable);
    doError(throwable);
  }
}
 
Example #3
Source File: Spouts.java    From cyclops with Apache License 2.0 6 votes vote down vote up
static  ReactiveSeq<Integer> interval(String cron,ScheduledExecutorService exec) {
    ReactiveSubscriber<Integer> sub = reactiveSubscriber();
    AtomicBoolean isOpen = new AtomicBoolean(true);
    Subscription[] s= {null};
    sub.onSubscribe(new Subscription() {
        @Override
        public void request(long n) {
            s[0].request(n);
        }

        @Override
        public void cancel() {
            isOpen.set(false);
        }
    });

    s[0] = ReactiveSeq.iterate(1, a -> a + 1)
                      .takeWhile(e -> isOpen.get())
                      .schedule(cron, exec)
                      .connect()
                      .forEach(1, e -> sub.onNext(e));

    return sub.reactiveStream();

}
 
Example #4
Source File: DeferredSubscription.java    From reactive-streams-commons with Apache License 2.0 6 votes vote down vote up
@Override
public void request(long n) {
    Subscription a = s;
    if (a != null) {
        a.request(n);
    } else {
        BackpressureHelper.getAndAddCap(REQUESTED, this, n);

        a = s;

        if (a != null) {
            long r = REQUESTED.getAndSet(this, 0L);

            if (r != 0L) {
                a.request(r);
            }
        }
    }
}
 
Example #5
Source File: MonoSubscribeOn.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Override
public void request(long n) {
	if (Operators.validate(n)) {
		Subscription a = s;
		if (a != null) {
			trySchedule(n, a);
		}
		else {
			Operators.addCap(REQUESTED, this, n);
			a = s;
			if (a != null) {
				long r = REQUESTED.getAndSet(this, 0L);
				if (r != 0L) {
					trySchedule(n, a);
				}
			}
		}
	}
}
 
Example #6
Source File: FileAsyncResponseTransformerTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void errorInStream_completesFuture() {
    Path testPath = testFs.getPath("test_file.txt");
    FileAsyncResponseTransformer xformer = new FileAsyncResponseTransformer(testPath);

    CompletableFuture prepareFuture = xformer.prepare();

    xformer.onResponse(new Object());
    xformer.onStream(subscriber -> {
        subscriber.onSubscribe(new Subscription() {
            @Override
            public void request(long l) {
            }

            @Override
            public void cancel() {
            }
        });

        subscriber.onError(new RuntimeException("Something went wrong"));
    });

    assertThat(prepareFuture.isCompletedExceptionally()).isTrue();
}
 
Example #7
Source File: FluxBufferBoundary.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
void otherError(Throwable t){
	Subscription s = S.getAndSet(this, Operators.cancelledSubscription());
	if(s != Operators.cancelledSubscription()) {
		C b;
		synchronized (this) {
			b = buffer;
			buffer = null;
		}

		if(s != null){
			s.cancel();
		}

		actual.onError(t);
		Operators.onDiscardMultiple(b, this.ctx);
		return;
	}
	Operators.onErrorDropped(t, this.ctx);
}
 
Example #8
Source File: FluxZipTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void scanSingleSubscriber() {
    CoreSubscriber<Integer> actual = new LambdaSubscriber<>(null, e -> {}, null, null);
    FluxZip.ZipSingleCoordinator<Integer, Integer> main =
new FluxZip.ZipSingleCoordinator<Integer, Integer>(actual, new Object[1], 1, i -> 5);
    FluxZip.ZipSingleSubscriber<Integer> test = new FluxZip.ZipSingleSubscriber<>(main, 0);
    Subscription parent = Operators.emptySubscription();
    test.onSubscribe(parent);

    Assertions.assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(parent);
    Assertions.assertThat(test.scan(Scannable.Attr.ACTUAL)).isSameAs(main);
    test.onNext(7);
    Assertions.assertThat(test.scan(Scannable.Attr.BUFFERED)).isEqualTo(1);
    Assertions.assertThat(test.scan(Scannable.Attr.TERMINATED)).isTrue();
    Assertions.assertThat(test.scan(Scannable.Attr.CANCELLED)).isTrue();
}
 
Example #9
Source File: MultiAssertSubscriberTest.java    From smallrye-mutiny with Apache License 2.0 6 votes vote down vote up
@Test
public void testItemsAndCompletion() {
    MultiAssertSubscriber<String> subscriber = MultiAssertSubscriber.create();
    Subscription subscription = mock(Subscription.class);
    subscriber.assertNotTerminated();
    subscriber.onSubscribe(subscription);
    subscriber.request(2);
    verify(subscription).request(2);
    subscriber.assertSubscribed();
    subscriber.onNext("a");
    subscriber.onNext("b");
    subscriber.onComplete();

    subscriber.assertReceived("a", "b")
            .assertCompletedSuccessfully()
            .assertHasNotFailed();
}
 
Example #10
Source File: AsyncSigV4SubscriberAdapter.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Override
public void onSubscribe(Subscription s) {
    delegate.onSubscribe(new Subscription() {
        @Override
        public void request(long n) {
            if (n <= 0) {
                throw new IllegalArgumentException("n > 0 required but it was " + n);
            }

            downstreamDemand.getAndAdd(n);

            if (upstreamDone.get()) {
                sendTrailingEmptyFrame();
            } else {
                s.request(n);
            }
        }

        @Override
        public void cancel() {
            s.cancel();
        }
    });
}
 
Example #11
Source File: MonoThenIgnoreTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void scanThenAcceptInner() {
	CoreSubscriber<String> actual = new LambdaMonoSubscriber<>(null, e -> {}, null, null);
	MonoIgnoreThen.ThenIgnoreMain<String> main = new MonoIgnoreThen.ThenIgnoreMain<>(actual, new Publisher[0], Mono.just("foo"));

	MonoIgnoreThen.ThenAcceptInner<String> test = new MonoIgnoreThen.ThenAcceptInner<>(main);
	Subscription parent = Operators.emptySubscription();
	test.onSubscribe(parent);

	assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(parent);
	assertThat(test.scan(Scannable.Attr.ACTUAL)).isSameAs(main);

	assertThat(test.scan(Scannable.Attr.TERMINATED)).isFalse();
	test.onError(new IllegalStateException("boom"));
	assertThat(test.scan(Scannable.Attr.TERMINATED)).isTrue();

	assertThat(test.scan(Scannable.Attr.CANCELLED)).isFalse();
	test.cancel();
	assertThat(test.scan(Scannable.Attr.CANCELLED)).isTrue();
}
 
Example #12
Source File: ITSpringConfiguredReactorClient.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
/**
 * This assumes that implementations do not issue an HTTP request until
 * {@link Subscription#request(long)} is called. Since a client span is only for
 * remote operations, we should not create one when we know a network request won't
 * happen. In this case, we ensure a canceled subscription doesn't end up traced.
 */
@Test
public void cancelledSubscription_doesntTrace() throws Exception {
	CountDownLatch latch = new CountDownLatch(1);

	BaseSubscriber<Integer> subscriber = new BaseSubscriber<Integer>() {
		@Override
		protected void hookOnSubscribe(Subscription subscription) {
			subscription.cancel();
			latch.countDown();
		}
	};

	getMono(client, "/foo").subscribe(subscriber);

	latch.await();

	assertThat(server.getRequestCount()).isZero();
	// post-conditions will prove no span was created
}
 
Example #13
Source File: WrappedSubscriptionTest.java    From smallrye-reactive-streams-operators with Apache License 2.0 6 votes vote down vote up
@Test
public void testWrappedSubscription() {
    Subscription subscription = new Subscription() {
        @Override
        public void request(long n) {

        }

        @Override
        public void cancel() {

        }
    };

    WrappedSubscription wrapped = new WrappedSubscription(subscription, null);
    assertThat(wrapped).isNotNull();
    wrapped.request(10);
    wrapped.cancel();
}
 
Example #14
Source File: Subscriptions.java    From smallrye-mutiny with Apache License 2.0 6 votes vote down vote up
/**
 * Atomically requests from the Subscription in the field if not null, otherwise accumulates
 * the request amount in the requested field to be requested once the field is set to non-null.
 *
 * @param field the target field that may already contain a Subscription
 * @param requested the current requested amount
 * @param requests the request amount, positive (verified)
 */
public static void requestIfNotNullOrAccumulate(AtomicReference<Subscription> field, AtomicLong requested, long requests) {
    Subscription subscription = field.get();
    if (subscription != null) {
        subscription.request(requests);
    } else {
        if (requests > 0) {
            add(requested, requests);
            subscription = field.get();
            if (subscription != null) {
                long r = requested.getAndSet(0L);
                if (r != 0L) {
                    subscription.request(r);
                }
            }
        }
    }
}
 
Example #15
Source File: FluxSampleTimeoutTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void scanMain() {
    CoreSubscriber<Integer> actual = new LambdaSubscriber<>(null, e -> {}, null, null);
    FluxSampleTimeout.SampleTimeoutMain<Integer, Integer> test =
    		new FluxSampleTimeout.SampleTimeoutMain<>(actual, i -> Flux.just(i),
    				Queues.<SampleTimeoutOther<Integer, Integer>>one().get());
    Subscription parent = Operators.emptySubscription();
    test.onSubscribe(parent);

    Assertions.assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(parent);
    Assertions.assertThat(test.scan(Scannable.Attr.ACTUAL)).isSameAs(actual);
    test.requested = 35;
    Assertions.assertThat(test.scan(Scannable.Attr.REQUESTED_FROM_DOWNSTREAM)).isEqualTo(35L);
    test.queue.add(new FluxSampleTimeout.SampleTimeoutOther<Integer, Integer>(test, 1, 0));
    Assertions.assertThat(test.scan(Scannable.Attr.BUFFERED)).isEqualTo(1);

    Assertions.assertThat(test.scan(Scannable.Attr.CANCELLED)).isFalse();
    Assertions.assertThat(test.scan(Scannable.Attr.TERMINATED)).isFalse();
    test.error = new IllegalStateException("boom");
    Assertions.assertThat(test.scan(Scannable.Attr.ERROR)).hasMessage("boom");
    test.onComplete();
    Assertions.assertThat(test.scan(Scannable.Attr.TERMINATED)).isTrue();
    Assertions.assertThat(test.scan(Scannable.Attr.CANCELLED)).isTrue();
}
 
Example #16
Source File: MonoUsingWhenTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void scanResourceSubscriber() {
	CoreSubscriber<Integer> actual = new LambdaSubscriber<>(null, e -> {}, null, null);
	ResourceSubscriber<String, Integer> op = new ResourceSubscriber<>(actual, s -> Mono.just(s.length()), Mono::just, (res, err) -> Mono.just(res), Mono::just, true);
	final Subscription parent = Operators.emptySubscription();
	op.onSubscribe(parent);

	assertThat(op.scan(Attr.PARENT)).as("PARENT").isSameAs(parent);
	assertThat(op.scan(Attr.ACTUAL)).as("ACTUAL").isSameAs(actual);

	assertThat(op.scan(Attr.PREFETCH)).as("PREFETCH").isEqualTo(Integer.MAX_VALUE);

	assertThat(op.scan(Attr.TERMINATED)).as("TERMINATED").isFalse();
	op.resourceProvided = true;
	assertThat(op.scan(Attr.TERMINATED)).as("TERMINATED resourceProvided").isTrue();

	assertThat(op.scanUnsafe(Attr.CANCELLED)).as("CANCELLED not supported").isNull();
}
 
Example #17
Source File: WrappedSubscriptionTest.java    From smallrye-mutiny with Apache License 2.0 6 votes vote down vote up
@Test
public void testWrappedSubscription() {
    Subscription subscription = new Subscription() {
        @Override
        public void request(long n) {

        }

        @Override
        public void cancel() {

        }
    };

    WrappedSubscription wrapped = new WrappedSubscription(subscription, null);
    assertThat(wrapped).isNotNull();
    wrapped.request(10);
    wrapped.cancel();
}
 
Example #18
Source File: FlatteningSubscriber.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Override
public void onSubscribe(Subscription subscription) {
    sourceSubscription = subscription;
    subscriber.onSubscribe(new Subscription() {
        @Override
        public void request(long l) {
            synchronized (lock) {
                demand.addAndGet(l);
                // Execution goes into `if` block only once for the initial request
                // After that requestedNextBatch is always true and more requests are made in fulfillDemand()
                if (!requestedNextBatch) {
                    requestedNextBatch = true;
                    sourceSubscription.request(1);
                } else {
                    fulfillDemand();
                }
            }
        }

        @Override
        public void cancel() {
            subscription.cancel();
        }
    });
}
 
Example #19
Source File: FluxGroupByTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void scanMain() {
	CoreSubscriber<GroupedFlux<Integer, String>> actual = new LambdaSubscriber<>(null, e -> {}, null, null);
	FluxGroupBy.GroupByMain<Integer, Integer, String> test = new FluxGroupBy.GroupByMain<>(actual,
			Queues.<GroupedFlux<Integer, String>>one().get(), Queues.one(), 123, i -> i % 5, i -> String.valueOf(i));
	Subscription sub = Operators.emptySubscription();
       test.onSubscribe(sub);

	assertThat(test.scan(Scannable.Attr.ACTUAL)).isSameAs(actual);
	assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(sub);
	assertThat(test.scan(Scannable.Attr.REQUESTED_FROM_DOWNSTREAM)).isEqualTo(Long.MAX_VALUE);
	assertThat(test.scan(Scannable.Attr.PREFETCH)).isSameAs(123);
	assertThat(test.scan(Scannable.Attr.BUFFERED)).isSameAs(0);
	assertThat(test.scan(Scannable.Attr.CANCELLED)).isFalse();
	assertThat(test.scan(Scannable.Attr.TERMINATED)).isFalse();
	assertThat(test.scan(Scannable.Attr.ERROR)).isNull();
	test.error = new IllegalStateException("boom");
	assertThat(test.scan(Scannable.Attr.ERROR)).isSameAs(test.error);
}
 
Example #20
Source File: MultiAssertSubscriberTest.java    From smallrye-mutiny with Apache License 2.0 6 votes vote down vote up
@Test
public void testAwaitOnFailure() {
    MultiAssertSubscriber<String> subscriber = MultiAssertSubscriber.create();
    Subscription subscription = mock(Subscription.class);

    subscriber.onSubscribe(subscription);
    subscriber.request(2);

    new Thread(() -> {
        subscriber.onNext("1");
        subscriber.onNext("2");
        subscriber.onError(new Exception("boom"));
    }).start();

    subscriber.await();
    subscriber.assertHasFailedWith(Exception.class, "boom");
}
 
Example #21
Source File: PublisherTakeUntilPredicate.java    From reactive-streams-commons with Apache License 2.0 5 votes vote down vote up
@Override
public void onSubscribe(Subscription s) {
    if (SubscriptionHelper.validate(this.s, s)) {
        this.s = s;
        actual.onSubscribe(this);
    }
}
 
Example #22
Source File: LambdaMonoSubscriber.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Override
public final void onComplete() {
	Subscription s = S.getAndSet(this, Operators.cancelledSubscription());
	if (s == Operators.cancelledSubscription()) {
		return;
	}
	if (completeConsumer != null) {
		try {
			completeConsumer.run();
		}
		catch (Throwable t) {
			Operators.onErrorDropped(t, this.initialContext);
		}
	}
}
 
Example #23
Source File: FluxDistinctUntilChangedTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void scanSubscriber() {
	CoreSubscriber<String> actual = new LambdaSubscriber<>(null, e -> {}, null, null);
	DistinctUntilChangedSubscriber<String, Integer> test = new DistinctUntilChangedSubscriber<>(
		actual, String::hashCode, Objects::equals);
	Subscription parent = Operators.emptySubscription();
	test.onSubscribe(parent);

	assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(parent);
	assertThat(test.scan(Scannable.Attr.ACTUAL)).isSameAs(actual);

	assertThat(test.scan(Scannable.Attr.TERMINATED)).isFalse();
	test.onError(new IllegalStateException("boom"));
	assertThat(test.scan(Scannable.Attr.TERMINATED)).isTrue();
}
 
Example #24
Source File: PersistentActor.java    From elasticactors with Apache License 2.0 5 votes vote down vote up
public void cancelSubscription(String messageName, ActorRef publisherRef) {
    if(persistentSubscriptions != null) {
        persistentSubscriptions.stream()
                .filter( p -> p.getMessageName().equals(messageName) && p.getPublisherRef().equals(publisherRef))
                .findFirst().ifPresent(Subscription::cancel);
    }
}
 
Example #25
Source File: MonoDoFirstTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void performsDirectSubscriberToSource_NoFusion() {
	AtomicReference<Subscription> subRef = new AtomicReference<>();
	Mono<Integer> test = Mono.just(1)
	                         .hide()
	                         .doFirst(() -> {})
	                         .doOnSubscribe(subRef::set);
	StepVerifier.create(test).expectNextCount(1).verifyComplete();

	assertThat(subRef.get().getClass()).isEqualTo(FluxHide.HideSubscriber.class);
}
 
Example #26
Source File: GroupedTest.java    From cyclops with Apache License 2.0 5 votes vote down vote up
@Test
public void limitPosition(){
    Spouts.iterate(0l, i->i+1l).grouped(1).map(l->l.getOrElse(0,-1l)).limit(5)
          .subscribe(new Subscriber<Long>() {
              @Override
              public void onSubscribe(Subscription s) {
                  sub = s;
              }

              @Override
              public void onNext(Long aLong) {
                  if(aLong.equals(2l))
                    System.out.println("Recieved " + aLong);
                  count.incrementAndGet();
              }

              @Override
              public void onError(Throwable t) {
                  error.incrementAndGet();
              }

              @Override
              public void onComplete() {
                  complete.incrementAndGet();
              }
          });

    sub.request(1l);
    assertThat(count.get(),equalTo(1));
    sub.request(1l);
    assertThat(count.get(),equalTo(2));
    assertThat(complete.get(),equalTo(0));

    sub.request(1l);
    assertThat(count.get(),equalTo(3));
    assertThat(complete.get(),equalTo(0));

}
 
Example #27
Source File: FluxDistinctTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void scanSubscriber() {
	CoreSubscriber<String> actual = new LambdaSubscriber<>(null, e -> {}, null, null);
	DistinctSubscriber<String, Integer, Set<Integer>> test =
			new DistinctSubscriber<>(actual, new HashSet<>(), String::hashCode, Set::add, Set::clear);
	Subscription parent = Operators.emptySubscription();
	test.onSubscribe(parent);

	assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(parent);
	assertThat(test.scan(Scannable.Attr.ACTUAL)).isSameAs(actual);

	assertThat(test.scan(Scannable.Attr.TERMINATED)).isFalse();
	test.onError(new IllegalStateException("boom"));
	assertThat(test.scan(Scannable.Attr.TERMINATED)).isTrue();
}
 
Example #28
Source File: IntDeferredReducerCore.java    From akarnokd-misc with Apache License 2.0 5 votes vote down vote up
@Override
public final void onSubscribe(Subscription s) {
    this.s = s;

    subscriber.onSubscribe(this);

    s.request(Long.MAX_VALUE);
}
 
Example #29
Source File: AsyncRSSequentialTest.java    From cyclops with Apache License 2.0 5 votes vote down vote up
@Test
public void subscribeErrorEmpty() throws InterruptedException {
    List result = new ArrayList<>();
    Subscription s= of().forEachSubscribe(i->result.add(i), e->e.printStackTrace());
    s.request(1l);
    sleep(10);
    assertThat(result.size(), Matchers.equalTo(0));
    s.request(1l);
    sleep(10);
    assertThat(result.size(), Matchers.equalTo(0));
    s.request(1l);
    sleep(10);
    assertThat(result.size(), Matchers.equalTo(0));

}
 
Example #30
Source File: WrappedProcessor.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@Override
public void onSubscribe(Subscription subscription) {
    Objects.requireNonNull(subscription);
    if (!subscribed.compareAndSet(false, true)) {
        subscription.cancel();
    } else {
        subscriber.onSubscribe(subscription);
    }
}