Java Code Examples for reactor.core.Disposable#dispose()

The following examples show how to use reactor.core.Disposable#dispose() . 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: FluxSubscribeOnValue.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)) {
		if (ONCE.compareAndSet(this, 0, 1)) {
			try {
				Disposable f = scheduler.schedule(this);
				if (!FUTURE.compareAndSet(this,
						null,
						f) && future != FINISHED && future != OperatorDisposables.DISPOSED) {
					f.dispose();
				}
			}
			catch (RejectedExecutionException ree) {
				if (future != FINISHED && future != OperatorDisposables.DISPOSED) {
					actual.onError(Operators.onRejectedExecution(ree,
							this,
							null,
							value, actual.currentContext()));
				}
			}
		}
	}
}
 
Example 2
Source File: WsClient.java    From reactor-workshop with GNU General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) throws URISyntaxException, InterruptedException {
    WebSocketClient client = new ReactorNettyWebSocketClient();

    URI url = new URI("ws://localhost:8080/time");
    final Mono<Void> reqResp = client
            .execute(url, session -> {
                Flux<WebSocketMessage> outMessages = Flux
                        .interval(Duration.ofSeconds(1))
                        .take(10)
                        .map(x -> "Message " + x)
                        .doOnNext(x -> log.info("About to send '{}'", x))
                        .map(session::textMessage);
                Mono<Void> receiving = session
                        .receive()
                        .map(WebSocketMessage::getPayloadAsText)
                        .doOnNext(x -> log.info("Received '{}'", x))
                        .then();
                return session.send(outMessages).mergeWith(receiving).then();
            });

    final Disposable disposable = reqResp.subscribe();
    TimeUnit.SECONDS.sleep(20);
    disposable.dispose();
}
 
Example 3
Source File: MonoCreate.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Override
public MonoSink<T> onCancel(Disposable d) {
	Objects.requireNonNull(d, "onCancel");
	SinkDisposable sd = new SinkDisposable(null, d);
	if (!DISPOSABLE.compareAndSet(this, null, sd)) {
		Disposable c = disposable;
		if (c == CANCELLED) {
			d.dispose();
		}
		else if (c instanceof SinkDisposable) {
			SinkDisposable current = (SinkDisposable) c;
			if (current.onCancel == null) {
				current.onCancel = d;
			}
			else {
				d.dispose();
			}
		}
	}
	return this;
}
 
Example 4
Source File: ServiceInstanceLogStreamingTest.java    From spring-cloud-app-broker with Apache License 2.0 5 votes vote down vote up
@Test
void shouldPublishEventOnDisconnect() {
	Disposable subscription = connectToLogsStreamEndpoint();

	await().atMost(Duration.ofSeconds(1))
		.untilAsserted(() -> assertThat(actualEnvelope.get()).isNotNull());

	subscription.dispose();

	await().atMost(Duration.ofSeconds(1))
		.untilAsserted(() -> assertThat(LogStreamingTestApp.isReceivedStopEvent()).isTrue());
}
 
Example 5
Source File: ReactorSerializedInvokerTest.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 5_000)
public void testCancellation() {
    AtomicReference<Object> resultRef = new AtomicReference<>();
    Disposable disposable = reactorSerializedInvoker.submit(Mono.delay(Duration.ofHours(1)).map(tick -> "First"))
            .doOnCancel(() -> resultRef.set("CANCELLED"))
            .subscribe(
                    resultRef::set,
                    resultRef::set
            );
    disposable.dispose();
    await().until(disposable::isDisposed);
    assertThat(resultRef.get()).isEqualTo("CANCELLED");
}
 
Example 6
Source File: FluxListenerInvocationHandlerTest.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
@Test
public void testCancellation() {
    Disposable subscription = ReactorExt.fromListener(EventListener.class, eventObservable::addListener, eventObservable::removeListener).subscribe();

    assertThat(eventObservable.eventHandler).isNotNull();
    subscription.dispose();
    assertThat(eventObservable.eventHandler).isNull();
}
 
Example 7
Source File: PublisherProbeTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void wasCancelledMono() {
	PublisherProbe<Void> probe = PublisherProbe.of(Mono.never());
	Disposable d = probe.mono().subscribe();

	assertThat(probe.wasCancelled()).isFalse();

	d.dispose();

	assertThat(probe.wasCancelled()).isTrue();
}
 
Example 8
Source File: OperatorDisposables.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
/**
 * Atomically set the field to the given non-null {@link Disposable} and return true,
 * or return false if the field is non-null.
 * If the target field contains the common {@link #DISPOSED} instance, the supplied disposable
 * is disposed. If the field contains other non-null {@link Disposable}, an {@link IllegalStateException}
 * is signalled to the {@code errorCallback}.
 *
 * @param updater the target field updater
 * @param holder the target instance holding the field
 * @param newValue the new Disposable to set, not null
 * @return true if the operation succeeded, false
 */
public static <T> boolean setOnce(AtomicReferenceFieldUpdater<T, Disposable> updater, T holder, Disposable newValue,
		Consumer<RuntimeException> errorCallback) {
	Objects.requireNonNull(newValue, "newValue is null");
	if (!updater.compareAndSet(holder, null, newValue)) {
		newValue.dispose();
		if (updater.get(holder) != DISPOSED) {
			errorCallback.accept(new IllegalStateException("Disposable already pushed"));
		}
		return false;
	}
	return true;
}
 
Example 9
Source File: FluxTests.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
/**
 * This test case demonstrates a silent failure of {@link Flux#interval(Duration)}
 * when a resolution is specified that
 * is less than the backing {@link Timer} class.
 *
 * @throws InterruptedException - on failure.
 * @throws TimeoutException     - on failure. <p> by @masterav10 : https://github.com/reactor/reactor/issues/469
 */
@Test
@Ignore
public void endLessTimer() throws InterruptedException, TimeoutException {
	int tasks = 50;
	long delayMS = 50; // XXX: Fails when less than 100
	Phaser barrier = new Phaser(tasks + 1);

	List<Long> times = new ArrayList<>();

	// long localTime = System.currentTimeMillis(); for java 7
	long localTime = Instant.now()
	                        .toEpochMilli();
	long elapsed = System.nanoTime();

	Disposable ctrl = Flux.interval(Duration.ofMillis(delayMS))
	                      .log("test")
	                      .map((signal) -> {
		                      return TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - elapsed);
	                      })
	                      .doOnNext((elapsedMillis) -> {
		                      times.add(localTime + elapsedMillis);
		                      barrier.arrive();
	                      })
	                      .subscribe();

	barrier.awaitAdvanceInterruptibly(barrier.arrive(), tasks * delayMS + 1000, TimeUnit.MILLISECONDS);
	ctrl.dispose();

	Assert.assertEquals(tasks, times.size());

	for (int i = 1; i < times.size(); i++) {
		Long prev = times.get(i - 1);
		Long time = times.get(i);

		Assert.assertTrue(prev > 0);
		Assert.assertTrue(time > 0);
		Assert.assertTrue("was " + (time - prev), time - prev <= delayMS * 1.2);
	}
}
 
Example 10
Source File: PublisherProbeTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void wasCancelledFlux() {
	PublisherProbe<Void> probe = PublisherProbe.of(Flux.never());
	Disposable d = probe.flux().subscribe();

	assertThat(probe.wasCancelled()).isFalse();

	d.dispose();

	assertThat(probe.wasCancelled()).isTrue();
}
 
Example 11
Source File: ServiceInstanceLogStreamingTest.java    From spring-cloud-app-broker with Apache License 2.0 5 votes vote down vote up
@Test
void shouldPublishWebSocketEndpoint() {
	Disposable subscription = connectToLogsStreamEndpoint();

	await().atMost(Duration.ofSeconds(1))
		.untilAsserted(() -> assertThat(actualEnvelope).hasValue(expectedEnvelope));

	subscription.dispose();
}
 
Example 12
Source File: ReactorEssentialsTest.java    From Hands-On-Reactive-Programming-in-Spring-5 with MIT License 5 votes vote down vote up
@Test
public void managingSubscription() throws InterruptedException {
    Disposable disposable = Flux.interval(Duration.ofMillis(50))
        .doOnCancel(() -> log.info("Cancelled"))
        .subscribe(
            data -> log.info("onNext: {}", data)
        );
    Thread.sleep(200);
    disposable.dispose();
}
 
Example 13
Source File: RSocketListenerImpl.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
@Override
public void stop() throws Exception {
    for (Disposable responder : responders) {
        responder.dispose();
    }
    status = -1;
}
 
Example 14
Source File: ReactivePersonRepositoryIntegrationTest.java    From spring-data-examples with Apache License 2.0 5 votes vote down vote up
/**
 * A tailable cursor streams data using {@link Flux} as it arrives inside the capped collection.
 */
@Test
public void shouldStreamDataWithTailableCursor() throws Exception {

	Queue<Person> people = new ConcurrentLinkedQueue<>();

	Disposable disposable = repository.findWithTailableCursorBy() //
			.doOnNext(System.out::println) //
			.doOnNext(people::add) //
			.doOnComplete(() -> System.out.println("Complete")) //
			.doOnTerminate(() -> System.out.println("Terminated")) //
			.subscribe();

	Thread.sleep(100);

	StepVerifier.create(repository.save(new Person("Tuco", "Salamanca", 33))) //
			.expectNextCount(1) //
			.verifyComplete();
	Thread.sleep(100);

	StepVerifier.create(repository.save(new Person("Mike", "Ehrmantraut", 62))) //
			.expectNextCount(1) //
			.verifyComplete();
	Thread.sleep(100);

	disposable.dispose();

	StepVerifier.create(repository.save(new Person("Gus", "Fring", 53))) //
			.expectNextCount(1) //
			.verifyComplete();
	Thread.sleep(100);

	assertThat(people).hasSize(6);
}
 
Example 15
Source File: SchedulersTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void testWorkerScheduleSupportZeroPeriodWithDelayPeriod() {
	try(TaskCheckingScheduledExecutor executorService = new TaskCheckingScheduledExecutor()) {
		Disposable.Composite tasks = Disposables.composite();
		Disposable disposable = Schedulers.workerSchedulePeriodically(executorService, tasks,
				() -> { }, 1000, 0, TimeUnit.MILLISECONDS);

		disposable.dispose();

		assertThat(executorService.isAllTasksCancelled()).isTrue();
	}
}
 
Example 16
Source File: UnicastProcessor.java    From reactor-core with Apache License 2.0 4 votes vote down vote up
void doTerminate() {
	Disposable r = onTerminate;
	if (r != null && ON_TERMINATE.compareAndSet(this, r, null)) {
		r.dispose();
	}
}
 
Example 17
Source File: AbstractSchedulerTest.java    From reactor-core with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 10000)
final public void workerScheduleAndDisposePeriod() throws Exception {
	Scheduler s = schedulerNotCached();
	Scheduler.Worker w = s.createWorker();

	try {
		assertThat(w.isDisposed()).isFalse();

		if (!shouldCheckWorkerTimeScheduling()) {
			assertThatExceptionOfType(RejectedExecutionException.class)
					.isThrownBy(() -> w.schedule(() -> { }, 10, TimeUnit.MILLISECONDS))
					.as("Worker marked as not supporting time scheduling")
					.isSameAs(Exceptions.failWithRejectedNotTimeCapable());
			return;
		}

		CountDownLatch latch = new CountDownLatch(1);
		CountDownLatch latch2 = new CountDownLatch(1);
		Disposable c = w.schedulePeriodically(() -> {
			try {
				latch.countDown();
				latch2.await(10, TimeUnit.SECONDS);
			}
			catch (InterruptedException e) {
			}
		}, 10, 10, TimeUnit.MILLISECONDS);
		Disposable d = c;
		//will throw if rejected

		latch.await();
		assertThat(d.isDisposed()).isFalse();
		d.dispose();

		Thread.yield();

		latch2.countDown();

		w.dispose();
		assertThat(w.isDisposed()).isTrue();

		assertThatExceptionOfType(RejectedExecutionException.class)
				.isThrownBy(() -> w.schedule(() -> { }))
				.isSameAs(Exceptions.failWithRejected());
	}
	finally {
		w.dispose();
		s.dispose();
	}
}
 
Example 18
Source File: FluxPublishTest.java    From reactor-core with Apache License 2.0 4 votes vote down vote up
@Test
public void disconnect() {
	AssertSubscriber<Integer> ts = AssertSubscriber.create();

	FluxIdentityProcessor<Integer> e = Processors.multicast();

	ConnectableFlux<Integer> p = e.publish();

	p.subscribe(ts);

	Disposable r = p.connect();

	e.onNext(1);
	e.onNext(2);

	r.dispose();

	ts.assertValues(1, 2)
	.assertError(CancellationException.class)
	.assertNotComplete();

	Assert.assertFalse("sp has subscribers?", e.downstreamCount() != 0);
}
 
Example 19
Source File: FluxRefCountGraceTest.java    From reactor-core with Apache License 2.0 4 votes vote down vote up
@Test
public void doesDisconnectAfterRefCountZeroAndSlowResubscribe()
		throws InterruptedException {
	AtomicLong subscriptionCount = new AtomicLong();
	AtomicReference<SignalType> termination = new AtomicReference<>();

	TestPublisher<Integer> publisher = TestPublisher.createNoncompliant(TestPublisher.Violation.CLEANUP_ON_TERMINATE);

	Flux<Integer> source = publisher.flux()
	                                .doFinally(termination::set)
	                                .doOnSubscribe(s -> subscriptionCount.incrementAndGet());

	Flux<Integer> refCounted = source.publish().refCount(2, Duration.ofMillis(500));

	Disposable sub1 = refCounted.subscribe();
	//initial subscribe doesn't reach the count
	assertThat(subscriptionCount.get()).isZero();
	assertThat(termination.get()).isNull();

	Disposable sub2 = refCounted.subscribe();
	//second subscribe does reaches the count
	assertThat(subscriptionCount.get()).isEqualTo(1);
	assertThat(termination.get()).isNull();

	sub1.dispose();
	//all subscribers are not disposed so source isn't terminated
	assertThat(subscriptionCount.get()).isEqualTo(1);
	assertThat(termination.get()).isNull();

	sub2.dispose();
	//all subscribers are now disposed, but grace period kicks in
	assertThat(subscriptionCount.get()).isEqualTo(1);
	assertThat(termination.get()).isNull();

	//we wait for grace period to elapse
	Thread.sleep(600);
	assertThat(termination.get()).isEqualTo(SignalType.CANCEL);
	termination.set(null);

	//we then resubscribe
	sub1 = refCounted.subscribe();
	sub2 = refCounted.subscribe();
	assertThat(subscriptionCount.get()).isEqualTo(2);

	//since the TestPublisher doesn't cleanup on termination, we can re-evaluate the doFinally
	publisher.complete();
	assertThat(termination.get()).isEqualTo(SignalType.ON_COMPLETE);
}
 
Example 20
Source File: FluxPublishTest.java    From reactor-core with Apache License 2.0 4 votes vote down vote up
@Test
public void disconnectBackpressured() {
	AssertSubscriber<Integer> ts = AssertSubscriber.create(0);

	FluxIdentityProcessor<Integer> e = Processors.multicast();

	ConnectableFlux<Integer> p = e.publish();

	p.subscribe(ts);

	Disposable r = p.connect();

	r.dispose();

	ts.assertNoValues()
	.assertError(CancellationException.class)
	.assertNotComplete();

	Assert.assertFalse("sp has subscribers?", e.downstreamCount() != 0);
}