Search in sources :

Example 56 with Subscriber

use of org.reactivestreams.Subscriber in project ratpack by ratpack.

the class ByteBufComposingPublisher method subscribe.

@Override
public void subscribe(Subscriber<? super CompositeByteBuf> subscriber) {
    subscriber.onSubscribe(new ManagedSubscription<CompositeByteBuf>(subscriber, ByteBuf::release) {

        private Subscription subscription;

        private CompositeByteBuf composite;

        private volatile State state;

        @Override
        protected void onRequest(long n) {
            if (subscription == null) {
                upstream.subscribe(new Subscriber<ByteBuf>() {

                    @Override
                    public void onSubscribe(Subscription s) {
                        subscription = s;
                        state = State.Fetching;
                        s.request(1);
                    }

                    @Override
                    public void onNext(ByteBuf t) {
                        if (state == State.Closed) {
                            t.release();
                            return;
                        }
                        if (composite == null) {
                            composite = alloc.compositeBuffer(maxNum);
                        }
                        composite.addComponent(true, t);
                        if (composite.numComponents() == maxNum || composite.readableBytes() >= watermark) {
                            state = State.Writing;
                            emitNext(composite);
                            composite = null;
                            maybeFetch();
                        } else {
                            subscription.request(1);
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        state = State.Closed;
                        ReferenceCountUtil.release(composite);
                        emitError(t);
                    }

                    @Override
                    public void onComplete() {
                        state = State.Closed;
                        if (composite != null) {
                            emitNext(composite);
                        }
                        emitComplete();
                    }
                });
            } else {
                maybeFetch();
            }
        }

        private void maybeFetch() {
            if (getDemand() > 0 && state != State.Fetching) {
                state = State.Fetching;
                subscription.request(1);
            }
        }

        @Override
        protected void onCancel() {
            state = State.Closed;
            ReferenceCountUtil.release(composite);
            if (subscription != null) {
                subscription.cancel();
            }
        }
    });
}
Also used : CompositeByteBuf(io.netty.buffer.CompositeByteBuf) Subscriber(org.reactivestreams.Subscriber) Subscription(org.reactivestreams.Subscription) ManagedSubscription(ratpack.stream.internal.ManagedSubscription) CompositeByteBuf(io.netty.buffer.CompositeByteBuf) ByteBuf(io.netty.buffer.ByteBuf)

Example 57 with Subscriber

use of org.reactivestreams.Subscriber in project reactor-core by reactor.

the class EmitterProcessorTest method test.

@Test
@Ignore
public void test() {
    Scheduler asyncGroup = Schedulers.single();
    FluxProcessor<String, String> emitter = EmitterProcessor.create();
    CountDownLatch requestReceived = new CountDownLatch(1);
    AtomicLong demand = new AtomicLong(0);
    Publisher<String> publisher = s -> s.onSubscribe(new Subscription() {

        @Override
        public void request(long n) {
            System.out.println("request: " + n + " " + s);
            demand.addAndGet(n);
            requestReceived.countDown();
        }

        @Override
        public void cancel() {
            System.out.println("cancel");
        }
    });
    Flux.from(publisher).subscribeOn(asyncGroup).subscribe(emitter);
    AssertSubscriber<String> subscriber = AssertSubscriber.create();
    emitter.subscribe(subscriber);
    int i = 0;
    for (; ; ) {
        if (getAndSub(demand, 1) != 0) {
            emitter.onNext("" + (i++));
        } else {
            System.out.println("NO REQUESTED: " + emitter);
            LockSupport.parkNanos(100_000_000);
        }
    }
}
Also used : Disposable(reactor.core.Disposable) StepVerifier(reactor.test.StepVerifier) Scannable(reactor.core.Scannable) Processor(org.reactivestreams.Processor) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Scheduler(reactor.core.scheduler.Scheduler) AtomicReference(java.util.concurrent.atomic.AtomicReference) Nullable(reactor.util.annotation.Nullable) ArrayList(java.util.ArrayList) Queues(reactor.util.concurrent.Queues) CoreSubscriber(reactor.core.CoreSubscriber) Attr(reactor.core.Scannable.Attr) CANCELLED(reactor.core.Scannable.Attr.CANCELLED) Schedulers(reactor.core.scheduler.Schedulers) Subscriber(org.reactivestreams.Subscriber) CyclicBarrier(java.util.concurrent.CyclicBarrier) Publisher(org.reactivestreams.Publisher) Test(org.junit.Test) TimeUnit(java.util.concurrent.TimeUnit) LockSupport(java.util.concurrent.locks.LockSupport) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicLong(java.util.concurrent.atomic.AtomicLong) List(java.util.List) Stream(java.util.stream.Stream) Ignore(org.junit.Ignore) Subscription(org.reactivestreams.Subscription) AssertSubscriber(reactor.test.subscriber.AssertSubscriber) TERMINATED(reactor.core.Scannable.Attr.TERMINATED) Assert(org.junit.Assert) Assert.assertEquals(org.junit.Assert.assertEquals) AtomicLong(java.util.concurrent.atomic.AtomicLong) Scheduler(reactor.core.scheduler.Scheduler) CountDownLatch(java.util.concurrent.CountDownLatch) Subscription(org.reactivestreams.Subscription) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 58 with Subscriber

use of org.reactivestreams.Subscriber in project reactor-core by reactor.

the class EmitterProcessorTest method testPerformance.

@Test
@Ignore
public void testPerformance() {
    FluxProcessor<String, String> emitter = EmitterProcessor.create();
    CountDownLatch requestReceived = new CountDownLatch(1);
    AtomicLong maxDelay = new AtomicLong(0);
    AtomicLong demand = new AtomicLong(0);
    Publisher<String> publisher = new Publisher<String>() {

        long lastTimeRequestReceivedNs = -1;

        @Override
        public void subscribe(Subscriber<? super String> s) {
            s.onSubscribe(new Subscription() {

                @Override
                public void request(long n) {
                    requestReceived.countDown();
                    long now = System.nanoTime();
                    if (lastTimeRequestReceivedNs > 0) {
                        maxDelay.set(now - lastTimeRequestReceivedNs);
                    }
                    lastTimeRequestReceivedNs = now;
                    demand.addAndGet(n);
                }

                @Override
                public void cancel() {
                    System.out.println("cancel");
                }
            });
        }
    };
    publisher.subscribe(emitter);
    AssertSubscriber<String> subscriber = AssertSubscriber.create();
    emitter.subscribe(subscriber);
    String buffer = "Hello";
    int i = 0;
    for (; ; ) {
        if (getAndSub(demand, 1) > 0) {
            emitter.onNext(buffer);
        }
        if (i++ % 1000000 == 0) {
            System.out.println("maxDelay: " + TimeUnit.MICROSECONDS.toMillis(maxDelay.get()) + " µs");
        }
    }
}
Also used : AtomicLong(java.util.concurrent.atomic.AtomicLong) CoreSubscriber(reactor.core.CoreSubscriber) Subscriber(org.reactivestreams.Subscriber) AssertSubscriber(reactor.test.subscriber.AssertSubscriber) Publisher(org.reactivestreams.Publisher) CountDownLatch(java.util.concurrent.CountDownLatch) Subscription(org.reactivestreams.Subscription) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 59 with Subscriber

use of org.reactivestreams.Subscriber in project reactor-core by reactor.

the class BaseOperatorTest method fluxFuseableAsyncState.

@SuppressWarnings("unchecked")
final Flux<O> fluxFuseableAsyncState(OperatorScenario<I, PI, O, PO> scenario, boolean conditional) {
    AtomicReference<Scannable> ref = new AtomicReference<>();
    Flux<I> source = this.fluxFuseableAsync(scenario).doOnSubscribe(s -> Scannable.from(s).actuals().skip(1).findFirst().ifPresent(t -> {
        ref.set(t);
        if (scenario.prefetch() != -1) {
            assertThat(t.scan(Scannable.Attr.PREFETCH)).isEqualTo(scenario.prefetch());
        }
    }));
    if (source.getPrefetch() != -1 && scenario.prefetch() != -1) {
        assertThat(Math.min(source.getPrefetch(), Integer.MAX_VALUE)).isEqualTo(scenario.prefetch());
    }
    PO f;
    f = applyStateScenario(scenario, conditional, source);
    return Flux.from(f).doOnSubscribe(parent -> {
        Scannable t = Scannable.from(parent);
        assertThat(t.scan(Scannable.Attr.ERROR)).isNull();
        assertThat(t.scanOrDefault(Scannable.Attr.TERMINATED, false)).isFalse();
        // noop path
        if (parent instanceof Subscriber) {
            ((Subscriber<I>) parent).onSubscribe(Operators.emptySubscription());
            ((Subscriber<I>) parent).onSubscribe(Operators.cancelledSubscription());
        }
        touchTreeState(parent);
    }).doOnComplete(() -> {
        if (ref.get() != null) {
            Scannable t = ref.get();
            if (scenario.shouldAssertPostTerminateState()) {
                assertThat(t.scanOrDefault(Scannable.Attr.TERMINATED, true)).isTrue();
            }
            touchTreeState(ref.get());
        }
    }).doOnNext(d -> touchTreeState(ref.get()));
}
Also used : UnicastProcessor(reactor.core.publisher.UnicastProcessor) StepVerifier(reactor.test.StepVerifier) Iterator(java.util.Iterator) Operators(reactor.core.publisher.Operators) Scannable(reactor.core.Scannable) Publisher(org.reactivestreams.Publisher) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Hooks(reactor.core.publisher.Hooks) Test(org.junit.Test) ParallelFlux(reactor.core.publisher.ParallelFlux) AtomicReference(java.util.concurrent.atomic.AtomicReference) ReplayProcessor(reactor.core.publisher.ReplayProcessor) Nullable(reactor.util.annotation.Nullable) Queues(reactor.util.concurrent.Queues) Consumer(java.util.function.Consumer) Flux(reactor.core.publisher.Flux) List(java.util.List) Fuseable(reactor.core.Fuseable) After(org.junit.After) Subscription(org.reactivestreams.Subscription) Exceptions(reactor.core.Exceptions) Collections(java.util.Collections) Subscriber(org.reactivestreams.Subscriber) Before(org.junit.Before) Subscriber(org.reactivestreams.Subscriber) Scannable(reactor.core.Scannable) AtomicReference(java.util.concurrent.atomic.AtomicReference)

Example 60 with Subscriber

use of org.reactivestreams.Subscriber in project NewPipe by TeamNewPipe.

the class SubscriptionsImportService method getSubscriber.

private Subscriber<List<SubscriptionEntity>> getSubscriber() {
    return new Subscriber<List<SubscriptionEntity>>() {

        @Override
        public void onSubscribe(Subscription s) {
            subscription = s;
            s.request(Long.MAX_VALUE);
        }

        @Override
        public void onNext(List<SubscriptionEntity> successfulInserted) {
            if (DEBUG)
                Log.d(TAG, "startImport() " + successfulInserted.size() + " items successfully inserted into the database");
        }

        @Override
        public void onError(Throwable error) {
            handleError(error);
        }

        @Override
        public void onComplete() {
            LocalBroadcastManager.getInstance(SubscriptionsImportService.this).sendBroadcast(new Intent(IMPORT_COMPLETE_ACTION));
            showToast(R.string.import_complete_toast);
            stopService();
        }
    };
}
Also used : Subscriber(org.reactivestreams.Subscriber) SubscriptionEntity(org.schabi.newpipe.database.subscription.SubscriptionEntity) ArrayList(java.util.ArrayList) List(java.util.List) Intent(android.content.Intent) Subscription(org.reactivestreams.Subscription)

Aggregations

Subscriber (org.reactivestreams.Subscriber)92 Subscription (org.reactivestreams.Subscription)56 Test (org.junit.Test)49 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)24 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)23 ProtonClient (io.vertx.proton.ProtonClient)22 ProtonConnection (io.vertx.proton.ProtonConnection)22 Message (org.apache.qpid.proton.message.Message)20 List (java.util.List)18 AmqpValue (org.apache.qpid.proton.amqp.messaging.AmqpValue)18 AtomicReference (java.util.concurrent.atomic.AtomicReference)17 Handler (io.vertx.core.Handler)16 Logger (io.vertx.core.impl.logging.Logger)16 LoggerFactory (io.vertx.core.impl.logging.LoggerFactory)16 ProtonStreams (io.vertx.proton.streams.ProtonStreams)16 ExecutionException (java.util.concurrent.ExecutionException)16 Symbol (org.apache.qpid.proton.amqp.Symbol)16 Section (org.apache.qpid.proton.amqp.messaging.Section)16 ArrayList (java.util.ArrayList)14 Collections (java.util.Collections)13