Java Code Examples for io.reactivex.Completable#subscribe()

The following examples show how to use io.reactivex.Completable#subscribe() . 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: ConnectFactoryTest.java    From rxmqtt with Apache License 2.0 7 votes vote down vote up
@Test
public void whenCreateIsCalledThenAnObservableIsReturned()
        throws Exception {
    final IMqttAsyncClient client = Mockito.mock(IMqttAsyncClient.class);
    final MqttConnectOptions options = Mockito
            .mock(MqttConnectOptions.class);
    final ConnectFactory factory = new ConnectFactory(client, options);
    final ArgumentCaptor<IMqttActionListener> actionListener = ArgumentCaptor
            .forClass(IMqttActionListener.class);
    final Completable obs = factory.create();
    Assert.assertNotNull(obs);
    obs.subscribe();
    Mockito.verify(client).connect(Matchers.same(options),
            Matchers.isNull(), actionListener.capture());
    Assert.assertTrue(actionListener
            .getValue() instanceof ConnectFactory.ConnectActionListener);
}
 
Example 2
Source File: CompletableOnSubscribeExecuteAsBlockingTest.java    From storio with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("ResourceType")
@Test
public void shouldExecuteAsBlockingAfterSubscription() {
    final PreparedCompletableOperation preparedOperation = mock(PreparedCompletableOperation.class);

    TestObserver testObserver = new TestObserver();

    verifyZeroInteractions(preparedOperation);

    Completable completable = Completable.create(new CompletableOnSubscribeExecuteAsBlocking(preparedOperation));

    verifyZeroInteractions(preparedOperation);

    completable.subscribe(testObserver);

    testObserver.assertNoErrors();
    testObserver.assertComplete();

    verify(preparedOperation).executeAsBlocking();
    verify(preparedOperation, never()).asRxFlowable(any(BackpressureStrategy.class));
    verify(preparedOperation, never()).asRxSingle();
    verify(preparedOperation, never()).asRxCompletable();
}
 
Example 3
Source File: CompletableUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenCompletableConstructed_thenCompletedSuccessfully() {
    Completable completed = Completable.complete();
    completed.subscribe(new DisposableCompletableObserver() {
        @Override
        public void onComplete() {
            System.out.println("Completed!");
        }

        @Override
        public void onError(Throwable e) {
            e.printStackTrace();
        }
    });
    Flowable<String> flowable = Flowable.just("request received", "user logged in");
    Completable flowableCompletable = Completable.fromPublisher(flowable);
    Completable singleCompletable = Single.just(1)
      .ignoreElement();

    completed.andThen(flowableCompletable)
      .andThen(singleCompletable)
      .test()
      .assertComplete();
}
 
Example 4
Source File: UnsubscribeFactoryTest.java    From rxmqtt with Apache License 2.0 6 votes vote down vote up
@Test
public void whenCreateIsCalledThenAnObservableIsReturned()
        throws Exception {
    // Given
    final IMqttAsyncClient client = Mockito.mock(IMqttAsyncClient.class);
    final UnsubscribeFactory factory = new UnsubscribeFactory(client);
    final String[] topics = new String[] { "topic1", "topic2" };
    final ArgumentCaptor<IMqttActionListener> actionListener = ArgumentCaptor
            .forClass(IMqttActionListener.class);

    // When
    final Completable obs = factory.create(topics);

    // Then
    Assert.assertNotNull(obs);
    obs.subscribe();
    Mockito.verify(client).unsubscribe(Matchers.same(topics),
            Matchers.isNull(), actionListener.capture());
    Assert.assertTrue(actionListener
            .getValue() instanceof UnsubscribeFactory.UnsubscribeActionListener);
}
 
Example 5
Source File: DisconnectFactoryTest.java    From rxmqtt with Apache License 2.0 6 votes vote down vote up
@Test
public void whenCreateIsCalledThenAnObservableIsReturned()
        throws Exception {
    // Given
    final IMqttAsyncClient client = Mockito.mock(IMqttAsyncClient.class);
    final DisconnectFactory factory = new DisconnectFactory(client);
    final ArgumentCaptor<IMqttActionListener> actionListener = ArgumentCaptor
            .forClass(IMqttActionListener.class);

    // When
    final Completable obs = factory.create();

    // Then
    Assert.assertNotNull(obs);
    obs.subscribe();
    Mockito.verify(client).disconnect(Matchers.isNull(),
            actionListener.capture());
    Assert.assertTrue(actionListener
            .getValue() instanceof DisconnectFactory.DisconnectActionListener);
}
 
Example 6
Source File: RxPgClientExamples.java    From vertx-rx with Apache License 2.0 6 votes vote down vote up
public void transaction01Example(PgPool pool) {

    Completable completable = pool.rxGetConnection()
      .flatMapCompletable(conn -> conn
        .rxBegin()
        .flatMapCompletable(tx ->
        conn
          .query("INSERT INTO Users (first_name,last_name) VALUES ('Julien','Viet')")
          .rxExecute()
          .flatMap(result -> conn
            .query("INSERT INTO Users (first_name,last_name) VALUES ('Emad','Alblueshi')")
            .rxExecute())
          .flatMapCompletable(res -> tx.rxCommit())
      ));

    completable.subscribe(() -> {
      // Transaction succeeded
    }, err -> {
      // Transaction failed
    });
  }
 
Example 7
Source File: ApiTest.java    From vertx-rx with Apache License 2.0 5 votes vote down vote up
@Test
public void testCompletable() {
  TestInterface obj = new TestInterface(new TestInterfaceImpl());
  Completable failure = obj.rxMethodWithHandlerAsyncResultVoid(true);
  AtomicInteger count = new AtomicInteger();
  failure.subscribe(Assert::fail, err -> {
    count.incrementAndGet();
  });
  assertEquals(1, count.getAndSet(0));
  Completable success = obj.rxMethodWithHandlerAsyncResultVoid(false);
  success.subscribe(count::incrementAndGet, err -> fail());
  assertEquals(1, count.get());
}
 
Example 8
Source File: AsyncResultAdapterTest.java    From vertx-rx with Apache License 2.0 5 votes vote down vote up
@Test
public void testCompletableReportingSubscribeUncheckedException() {
  RuntimeException cause = new RuntimeException();
  MethodWithCompletable meth = new MethodWithCompletable(handler -> {
    throw cause;
  });
  Completable single = meth.rxDoSomethingWithResult();
  single.subscribe(this::fail, err -> testComplete());
  await();
}
 
Example 9
Source File: HelperTest.java    From vertx-rx with Apache License 2.0 5 votes vote down vote up
@Test
public void testToCompletableObserverFailure() {
  Promise<String> promise = Promise.promise();
  CompletableObserver observer = CompletableHelper.toObserver(promise);
  RuntimeException cause = new RuntimeException();
  Completable s = Completable.error(cause);
  s.subscribe(observer);
  assertTrue(promise.future().failed());
  assertSame(cause, promise.future().cause());
}
 
Example 10
Source File: AbstractVerticle.java    From vertx-rx with Apache License 2.0 5 votes vote down vote up
@Override
public void stop(Promise<Void> stopFuture) throws Exception {
  Completable completable = rxStop();
  if (completable != null) {
    completable.subscribe(stopFuture::complete, stopFuture::fail);
  } else {
    super.stop(stopFuture);
  }
}
 
Example 11
Source File: AbstractVerticle.java    From vertx-rx with Apache License 2.0 5 votes vote down vote up
@Override
public void start(Promise<Void> startFuture) throws Exception {
  Completable completable = rxStart();
  if (completable != null) {
    completable.subscribe(startFuture::complete, startFuture::fail);
  } else {
    super.start(startFuture);
  }
}
 
Example 12
Source File: Rx2RetrofitInterceptorTest.java    From Mockery with Apache License 2.0 5 votes vote down vote up
private void checkDelayCompletable(Completable single, long millisDelayed) {
  long startNanos = System.nanoTime();

  TestObserver subscriber = new TestObserver();
  single.subscribe(subscriber);
  subscriber.awaitTerminalEvent();

  long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos);

  assertTrue("Mismatch delayed. TookMs: " + tookMs
      + " MillisDelayed: " + millisDelayed, tookMs >= millisDelayed);
}
 
Example 13
Source File: CloseFactoryTest.java    From rxmqtt with Apache License 2.0 5 votes vote down vote up
@Test
public void whenCreateIsCalledThenAnObservableIsReturned()
        throws Exception {
    // Given
    final IMqttAsyncClient client = Mockito.mock(IMqttAsyncClient.class);
    final CloseFactory factory = new CloseFactory(client);

    // When
    final Completable obs = factory.create();

    // Then
    Assert.assertNotNull(obs);
    obs.subscribe();
    Mockito.verify(client).close();
}
 
Example 14
Source File: RestfulApiVerticle.java    From vertx-blueprint-todo-backend with Apache License 2.0 5 votes vote down vote up
/**
 * Resolve an asynchronous status and send back the response.
 * The successful status code depends on processor {@code f}.
 *
 * @param context     routing context
 * @param asyncResult asynchronous status with no result
 */
protected void sendResponse(RoutingContext context, Completable asyncResult, Consumer<RoutingContext> f) {
  if (asyncResult == null) {
    internalError(context, "invalid_status");
  } else {
    asyncResult.subscribe(() -> f.accept(context), ex -> internalError(context, ex));
  }
}
 
Example 15
Source File: RestfulApiVerticle.java    From vertx-blueprint-todo-backend with Apache License 2.0 5 votes vote down vote up
/**
 * Resolve an asynchronous status and send back the response.
 * By default, the successful status code is 200 OK.
 *
 * @param context     routing context
 * @param asyncResult asynchronous status with no result
 */
protected void sendResponse(RoutingContext context, Completable asyncResult) {
  HttpServerResponse response = context.response();
  if (asyncResult == null) {
    internalError(context, "invalid_status");
  } else {
    asyncResult.subscribe(response::end, ex -> internalError(context, ex));
  }
}
 
Example 16
Source File: MainActivity.java    From Reactive-Android-Programming with MIT License 5 votes vote down vote up
private void demo5() {
    Completable completable = Completable.fromAction(() -> {
        log("Let's do something");
    });

    completable.subscribe(() -> {
        log("Finished");
    }, throwable -> {
        log(throwable);
    });


    Single.just("One item")
            .subscribe((item) -> {
                log(item);
            }, (throwable) -> {
                log(throwable);
            });

    Maybe.empty();
    Maybe.just("Item")
            .subscribe(s -> {
                log("On Success: " + s);
            });

    Maybe.just("Item")
            .subscribe(s -> {
                log("On Success: " + s);
            }, throwable -> log("error"));

    Maybe.just("Item")
            .subscribe(
                    s -> log("success: " + s),
                    throwable -> log("error"),
                    () -> log("onComplete")
            );
}
 
Example 17
Source File: CompletableConverter.java    From smallrye-reactive-streams-operators with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T> CompletionStage<T> toCompletionStage(Completable instance) {
    CompletableFuture<T> future = new CompletableFuture<>();
    Completable s = Objects.requireNonNull(instance);
    //noinspection ResultOfMethodCallIgnored
    s.subscribe(
            () -> future.complete(null),
            future::completeExceptionally);
    return future;
}
 
Example 18
Source File: CompletableOnSubscribeExecuteAsBlockingTest.java    From storio with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({"ThrowableInstanceNeverThrown", "ResourceType"})
@Test
public void shouldCallOnErrorIfExceptionOccurred() {
    final PreparedCompletableOperation preparedOperation = mock(PreparedCompletableOperation.class);

    StorIOException expectedException = new StorIOException("test exception");

    when(preparedOperation.executeAsBlocking()).thenThrow(expectedException);

    TestObserver testObserver = new TestObserver();

    Completable completable = Completable.create(new CompletableOnSubscribeExecuteAsBlocking(preparedOperation));

    verifyZeroInteractions(preparedOperation);

    completable.subscribe(testObserver);

    testObserver.assertError(expectedException);
    testObserver.assertNotComplete();

    verify(preparedOperation).executeAsBlocking();
    verify(preparedOperation, never()).asRxFlowable(any(BackpressureStrategy.class));
    verify(preparedOperation, never()).asRxSingle();
    verify(preparedOperation, never()).asRxCompletable();
}
 
Example 19
Source File: CompletableProvider.java    From redpipe with Apache License 2.0 4 votes vote down vote up
public CompletableAdaptor(Completable observable)
{
    this.subscription = observable.subscribe(this::completeEmpty, this::completeExceptionally);
}
 
Example 20
Source File: DemoCompletable.java    From Reactive-Programming-With-Java-9 with MIT License 3 votes vote down vote up
public static void main(String[] args) {
	// TODO Auto-generated method stub
	Completable completable = Completable.fromAction(() -> System.out.println("Welcome to Completable"));
	completable.subscribe();

	
}