All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.salesforce.reactivegrpccommon.ReactiveConsumerStreamObserver Maven / Gradle / Ivy

/*
 *  Copyright (c) 2017, salesforce.com, inc.
 *  All rights reserved.
 *  Licensed under the BSD 3-Clause license.
 *  For full license text, see LICENSE.txt file in the repo root  or https://opensource.org/licenses/BSD-3-Clause
 */

package com.salesforce.reactivegrpccommon;

import com.google.common.base.Preconditions;
import io.grpc.Status;
import io.grpc.stub.ClientCallStreamObserver;
import io.grpc.stub.ClientResponseObserver;
import org.reactivestreams.Publisher;

import java.util.concurrent.CountDownLatch;

/**
 * ReactorConsumerStreamObserver configures client-side manual flow control for the consuming end of a message stream.
 *
 * @param 
 * @param 
 */
public abstract class ReactiveConsumerStreamObserver implements ClientResponseObserver {
    private ReactiveStreamObserverPublisher publisher;
    private Publisher rxConsumer;
    private CountDownLatch beforeStartCalled = new CountDownLatch(1);

    public abstract Publisher getReactiveConsumerFromPublisher(ReactiveStreamObserverPublisher publisher);

    public Publisher getRxConsumer() {
        try {
            beforeStartCalled.await();
        } catch (InterruptedException e) {
            throw Status.INTERNAL.withCause(e).asRuntimeException();
        }
        return rxConsumer;
    }


    @Override
    public void beforeStart(ClientCallStreamObserver requestStream) {
        publisher = new ReactiveStreamObserverPublisher<>(Preconditions.checkNotNull(requestStream));
        rxConsumer = getReactiveConsumerFromPublisher(publisher);
        beforeStartCalled.countDown();
    }

    @Override
    public void onNext(TResponse value) {
        Preconditions.checkState(publisher != null, "beforeStart() not yet called");
        publisher.onNext(Preconditions.checkNotNull(value));
    }

    @Override
    public void onError(Throwable throwable) {
        Preconditions.checkState(publisher != null, "beforeStart() not yet called");
        publisher.onError(Preconditions.checkNotNull(throwable));
    }

    @Override
    public void onCompleted() {
        Preconditions.checkState(publisher != null, "beforeStart() not yet called");
        publisher.onCompleted();
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy