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

The following examples show how to use io.reactivex.Completable#create() . 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: Rx2Apollo.java    From apollo-android with MIT License 6 votes vote down vote up
/**
 * Converts an {@link ApolloPrefetch} to a synchronous Completable
 *
 * @param prefetch the ApolloPrefetch to convert
 * @return the converted Completable
 * @throws NullPointerException if prefetch == null
 */
@NotNull
@CheckReturnValue
public static Completable from(@NotNull final ApolloPrefetch prefetch) {
  checkNotNull(prefetch, "prefetch == null");

  return Completable.create(new CompletableOnSubscribe() {
    @Override public void subscribe(final CompletableEmitter emitter) {
      cancelOnCompletableDisposed(emitter, prefetch);
      prefetch.enqueue(new ApolloPrefetch.Callback() {
        @Override public void onSuccess() {
          if (!emitter.isDisposed()) {
            emitter.onComplete();
          }
        }

        @Override public void onFailure(@NotNull ApolloException e) {
          Exceptions.throwIfFatal(e);
          if (!emitter.isDisposed()) {
            emitter.onError(e);
          }
        }
      });
    }
  });
}
 
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: LogOutCallFactory.java    From dhis2-android-sdk with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public Completable logOut() {
    return Completable.create(emitter -> {
        Credentials credentials = this.credentialsSecureStore.get();

        if (credentials == null) {
            throw D2Error.builder()
                    .errorCode(D2ErrorCode.NO_AUTHENTICATED_USER)
                    .errorDescription("There is not any authenticated user")
                    .errorComponent(D2ErrorComponent.SDK)
                    .build();
        }

        databaseAdapterFactory.removeDatabaseAdapter(databaseAdapter);

        this.credentialsSecureStore.remove();
        emitter.onComplete();
    });
}
 
Example 4
Source File: MaybeConsumers.java    From science-journal with Apache License 2.0 6 votes vote down vote up
/**
 * Given an operation that takes a {@link MaybeConsumer<Success>}, create a JavaRX {@link
 * Completable} that succeeds iff the operation does.
 *
 * <p>Example:
 *
 * <pre>
 *     // update the experiment, and then log that it was successful
 *     DataController dc = getDataController();
 *     MaybeConsumers.buildCompleteable(mc -> dc.updateExperiment(e.getExperimentId(), mc))
 *                   .subscribe(() -> log("successfully updated!"));
 * </pre>
 */
public static Completable buildCompleteable(
    io.reactivex.functions.Consumer<MaybeConsumer<Success>> c) {
  return Completable.create(
      new CompletableOnSubscribe() {
        @Override
        public void subscribe(CompletableEmitter emitter) throws Exception {
          c.accept(
              new MaybeConsumer<Success>() {
                @Override
                public void success(Success value) {
                  emitter.onComplete();
                }

                @Override
                public void fail(Exception e) {
                  emitter.onError(e);
                }
              });
        }
      });
}
 
Example 5
Source File: RxActionDelegate.java    From pandroid with Apache License 2.0 6 votes vote down vote up
public static Completable completable(final OnSubscribeAction<Void> subscribe){
    return Completable.create(new CompletableOnSubscribe() {
        @Override
        public void subscribe(final CompletableEmitter emitter) throws Exception {
            RxActionDelegate<Void> delegate = new RxActionDelegate<>(new ActionDelegate<Void>() {
                @Override
                public void onSuccess(Void result) {
                    emitter.onComplete();
                }

                @Override
                public void onError(Exception e) {
                    emitter.onError(e);
                }
            });
            emitter.setDisposable(delegate);
            subscribe.subscribe(delegate);
        }
    });
}
 
Example 6
Source File: AddAssetInteractor.java    From iroha-android with Apache License 2.0 5 votes vote down vote up
@Override
protected Completable build(String details) {
    return Completable.create(emitter -> {
        long currentTime = System.currentTimeMillis();
        Keypair adminKeys = crypto.convertFromExisting(PUB_KEY, PRIV_KEY);
        String username = preferenceUtils.retrieveUsername();

        //Adding asset
        UnsignedTx addAssetTx = txBuilder.creatorAccountId(CREATOR)
                .createdTime(BigInteger.valueOf(currentTime))
                .addAssetQuantity(CREATOR, ASSET_ID, "100")
                .transferAsset(CREATOR, username + "@" + DOMAIN_ID, ASSET_ID, "initial", "100")
                .build();

        protoTxHelper = new ModelProtoTransaction(addAssetTx);
        ByteVector txblob = protoTxHelper.signAndAddSignature(adminKeys).finish().blob();
        byte[] bsq = toByteArray(txblob);
        BlockOuterClass.Transaction protoTx = null;

        try {
            protoTx = BlockOuterClass.Transaction.parseFrom(bsq);
        } catch (InvalidProtocolBufferException e) {
            emitter.onError(e);
        }

        CommandServiceGrpc.CommandServiceBlockingStub stub = CommandServiceGrpc.newBlockingStub(channel)
                .withDeadlineAfter(CONNECTION_TIMEOUT_SECONDS, TimeUnit.SECONDS);

        stub.torii(protoTx);

        // Check if it was successful
        if (!isTransactionSuccessful(stub, addAssetTx)) {
            emitter.onError(new RuntimeException("Transaction failed"));
        } else {
            emitter.onComplete();
        }
    });
}
 
Example 7
Source File: UnsubscribeFactory.java    From rxmqtt with Apache License 2.0 5 votes vote down vote up
public Completable create(final String[] topics) {

        return Completable.create(emitter -> {
            try {
                this.client.unsubscribe(topics, null,
                        new UnsubscribeActionListener(emitter));
            } catch (final MqttException exception) {
                if (LOGGER.isLoggable(Level.SEVERE)) {
                    LOGGER.log(Level.SEVERE, exception.getMessage(), exception);
                }
                emitter.onError(exception);
            }
        });
    }
 
Example 8
Source File: RxNeuroSky.java    From neurosky-android-sdk with Apache License 2.0 5 votes vote down vote up
public Completable start() {
  return Completable.create(emitter -> {
    if (preconditions.isConnected(device)) {
      startMonitoring();
      emitter.onComplete();
    } else {
      emitter.onError(new BluetoothNotConnectedException());
    }
  });
}
 
Example 9
Source File: RxJavaUtils.java    From storio with Apache License 2.0 5 votes vote down vote up
@CheckResult
@NonNull
public static <Result, Data> Completable createCompletable(
        @NonNull StorIOContentResolver storIOContentResolver,
        @NonNull PreparedCompletableOperation<Result, Data> operation
) {
    throwExceptionIfRxJava2IsNotAvailable("asRxCompletable()");

    final Completable completable = Completable.create(new CompletableOnSubscribeExecuteAsBlocking(operation));

    return subscribeOn(
            storIOContentResolver,
            completable
    );
}
 
Example 10
Source File: DefaultRx2ElasticSearchAdminService.java    From vertx-elasticsearch-service with Apache License 2.0 5 votes vote down vote up
@Override
public Completable createIndex(String index, JsonObject source, CreateIndexOptions options) {
    return Completable.create(handler -> {
        elasticSearchAdminService.createIndex(index, source, options, response -> {
            if (response.succeeded()) {
                handler.onComplete();
            } else {
                handler.onError(response.cause());
            }
        });
    });
}
 
Example 11
Source File: AppInitHelperBase.java    From edslite with GNU General Public License v2.0 5 votes vote down vote up
public static Completable createObservable(RxActivity activity)
{
    return Completable.create(emitter -> {
        AppInitHelper initHelper = new AppInitHelper(activity, emitter);
        initHelper.startInitSequence();
    });
}
 
Example 12
Source File: LoadingProgressDialog.java    From edslite with GNU General Public License v2.0 5 votes vote down vote up
public static Completable createObservable(Context context, boolean isCancellable)
{
    return Completable.create(emitter -> {
        Dialog dialog = makeProgressDialog(context);
        dialog.setCancelable(isCancellable);
        if(isCancellable)
            dialog.setOnCancelListener((dialogInterface) -> {
                throw new CancellationException();
            });
        emitter.setCancellable(dialog::dismiss);
        if(!emitter.isDisposed())
            dialog.show();
    });
}
 
Example 13
Source File: RxSessionClientImpl.java    From samples-android with Apache License 2.0 5 votes vote down vote up
@Override
public Completable migrateTo(EncryptionManager encryptionManager) {
    return Completable.create(emitter -> {
        mSyncSessionClient.migrateTo(encryptionManager);
        emitter.onComplete();
    });
}
 
Example 14
Source File: RxJavaUtils.java    From storio with Apache License 2.0 5 votes vote down vote up
@CheckResult
@NonNull
public static <T, Data> Completable createCompletable(
        @NonNull StorIOSQLite storIOSQLite,
        @NonNull PreparedCompletableOperation<T, Data> operation
) {
    throwExceptionIfRxJava2IsNotAvailable("asRxCompletable()");

    final Completable completable =
            Completable.create(new CompletableOnSubscribeExecuteAsBlocking(operation));

    return subscribeOn(storIOSQLite, completable);
}
 
Example 15
Source File: DefaultRx2ElasticSearchAdminService.java    From vertx-elasticsearch-service with Apache License 2.0 5 votes vote down vote up
@Override
public Completable deleteTemplate(String name, TemplateOptions options) {
    return Completable.create(handler -> {
        elasticSearchAdminService.deleteTemplate(name, options, response -> {
            if (response.succeeded()) {
                handler.onComplete();
            } else {
                handler.onError(response.cause());
            }
        });
    });
}
 
Example 16
Source File: DefaultRx2ElasticSearchAdminService.java    From vertx-elasticsearch-service with Apache License 2.0 5 votes vote down vote up
@Override
public Completable putTemplate(String name, JsonObject source, TemplateOptions options) {
    return Completable.create(handler -> {
        elasticSearchAdminService.putTemplate(name, source, options, response -> {
            if (response.succeeded()) {
                handler.onComplete();
            } else {
                handler.onError(response.cause());
            }
        });
    });
}
 
Example 17
Source File: OTPFactorProvider.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
public Completable verify(String secretKey, String code) {
    return Completable.create(emitter -> {
        try {
            final String otpCode = TOTP.generateTOTP(SharedSecret.base32Str2Hex(secretKey));
            if (!code.equals(otpCode)) {
                emitter.onError(new InvalidCodeException("Invalid 2FA Code"));
            }
            emitter.onComplete();
        } catch (Exception ex) {
            logger.error("An error occurs while validating 2FA code", ex);
            emitter.onError(new InvalidCodeException("Invalid 2FA Code"));
        }
    });
}
 
Example 18
Source File: SettingsManager.java    From ground-android with Apache License 2.0 5 votes vote down vote up
private Completable startResolution(int requestCode, ResolvableApiException resolvableException) {
  return Completable.create(
      em -> {
        Log.d(TAG, "Prompting user to enable settings");
        activityStreams.withActivity(
            act -> {
              try {
                resolvableException.startResolutionForResult(act, requestCode);
                em.onComplete();
              } catch (SendIntentException e) {
                em.onError(e);
              }
            });
      });
}
 
Example 19
Source File: SendAssetInteractor.java    From iroha-android with Apache License 2.0 5 votes vote down vote up
@Override
protected Completable build(String[] data) {
    return Completable.create(emitter -> {
        long currentTime = System.currentTimeMillis();
        Keypair userKeys = preferenceUtils.retrieveKeys();
        String username = preferenceUtils.retrieveUsername();
        //Sending asset
        UnsignedTx sendAssetTx = txBuilder.creatorAccountId(username + "@" + DOMAIN_ID)
                .createdTime(BigInteger.valueOf(currentTime))
                .transferAsset(username + "@" + DOMAIN_ID,
                        data[0] + "@" + DOMAIN_ID, ASSET_ID, "initial", data[1])
                .build();

        protoTxHelper = new ModelProtoTransaction(sendAssetTx);
        ByteVector txblob = protoTxHelper.signAndAddSignature(userKeys).finish().blob();
        byte[] bsq = toByteArray(txblob);
        BlockOuterClass.Transaction protoTx = null;

        try {
            protoTx = BlockOuterClass.Transaction.parseFrom(bsq);
        } catch (InvalidProtocolBufferException e) {
            emitter.onError(e);
        }

        CommandServiceGrpc.CommandServiceBlockingStub stub = CommandServiceGrpc.newBlockingStub(channel)
                .withDeadlineAfter(CONNECTION_TIMEOUT_SECONDS, TimeUnit.SECONDS);
        stub.torii(protoTx);

        // Check if it was successful
        if (!isTransactionSuccessful(stub, sendAssetTx)) {
            emitter.onError(new RuntimeException("Transaction failed"));
        } else {
            emitter.onComplete();
        }
    });
}
 
Example 20
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();
}