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

The following examples show how to use io.reactivex.Maybe#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: ToMaybe.java    From smallrye-mutiny with Apache License 2.0 6 votes vote down vote up
@Override
public Maybe<T> apply(Uni<T> uni) {
    return Maybe.create(emitter -> {
        CompletableFuture<T> future = uni.subscribe().asCompletionStage();
        emitter.setCancellable(() -> future.cancel(false));
        future.whenComplete((res, fail) -> {
            if (future.isCancelled()) {
                return;
            }

            if (fail != null) {
                emitter.onError(fail);
            } else if (res != null) {
                emitter.onSuccess(res);
                emitter.onComplete();
            } else {
                emitter.onComplete();
            }

        });
    });
}
 
Example 2
Source File: IdentityProviderPluginServiceImpl.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
public Maybe<String> getSchema(String identityProviderId) {
    LOGGER.debug("Find identity provider plugin schema by ID: {}", identityProviderId);
    return Maybe.create(emitter -> {
        try {
            String schema = identityProviderPluginManager.getSchema(identityProviderId);
            if (schema != null) {
                emitter.onSuccess(schema);
            } else {
                emitter.onComplete();
            }
        } catch (Exception e) {
            LOGGER.error("An error occurs while trying to get schema for identity provider plugin {}", identityProviderId, e);
            emitter.onError(new TechnicalManagementException("An error occurs while trying to get schema for identity provider plugin " + identityProviderId, e));
        }
    });
}
 
Example 3
Source File: IdentityProviderPluginServiceImpl.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
public Maybe<IdentityProviderPlugin> findById(String identityProviderId) {
    LOGGER.debug("Find identity provider plugin by ID: {}", identityProviderId);
    return Maybe.create(emitter -> {
        try {
            Plugin identityProvider = identityProviderPluginManager.findById(identityProviderId);
            if (identityProvider != null) {
                emitter.onSuccess(convert(identityProvider));
            } else {
                emitter.onComplete();
            }
        } catch (Exception ex) {
            LOGGER.error("An error occurs while trying to get identity provider plugin : {}", identityProviderId, ex);
            emitter.onError(new TechnicalManagementException("An error occurs while trying to get identity provider plugin : " + identityProviderId, ex));
        }
    });
}
 
Example 4
Source File: Query.java    From sqlitemagic with Apache License 2.0 6 votes vote down vote up
/**
 * Creates {@link Maybe} that when subscribed to executes the query against a database
 * and emits query result to downstream.
 * <p>
 * The resulting stream will be empty if query result is {@code null}.
 * <dl>
 * <dt><b>Scheduler:</b></dt>
 * <dd>{@code run} does not operate by default on a particular {@link Scheduler}.</dd>
 * </dl>
 *
 * @return Deferred {@link Maybe} that when subscribed to executes the query and emits
 * its result to downstream
 * @see #runBlocking
 */
@NonNull
@CheckResult
public final Maybe<T> run() {
  return Maybe.create(new MaybeOnSubscribe<T>() {
    @Override
    public void subscribe(MaybeEmitter<T> emitter) {
      final Cursor cursor = rawQuery(true);
      if (emitter.isDisposed()) {
        if (cursor != null) {
          cursor.close();
        }
        return;
      }
      final T result = map(cursor);
      if (result != null) {
        emitter.onSuccess(result);
      } else {
        emitter.onComplete();
      }
    }
  });
}
 
Example 5
Source File: MaybeOnSubscribeExecuteAsBlockingTest.java    From storio with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("CheckResult")
@Test
public void shouldExecuteAsBlockingAfterSubscription() {
    //noinspection unchecked
    final PreparedMaybeOperation<String, String, String> preparedOperation = mock(PreparedMaybeOperation.class);
    String expectedResult = "test";
    when(preparedOperation.executeAsBlocking()).thenReturn(expectedResult);

    TestObserver<String> testObserver = new TestObserver<String>();

    verifyZeroInteractions(preparedOperation);

    Maybe<String> maybe = Maybe.create(new MaybeOnSubscribeExecuteAsBlocking<String, String, String>(preparedOperation));

    verifyZeroInteractions(preparedOperation);

    maybe.subscribe(testObserver);

    testObserver.assertValue(expectedResult);
    testObserver.assertNoErrors();
    testObserver.assertComplete();

    verify(preparedOperation).executeAsBlocking();
}
 
Example 6
Source File: FactorPluginServiceImpl.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
public Maybe<String> getSchema(String factorId) {
    LOGGER.debug("Find authenticator plugin schema by ID: {}", factorId);
    return Maybe.create(emitter -> {
        try {
            String schema = factorPluginManager.getSchema(factorId);
            if (schema != null) {
                emitter.onSuccess(schema);
            } else {
                emitter.onComplete();
            }
        } catch (Exception e) {
            LOGGER.error("An error occurs while trying to get schema for factor plugin {}", factorId, e);
            emitter.onError(new TechnicalManagementException("An error occurs while trying to get schema for factor plugin " + factorId, e));
        }
    });
}
 
Example 7
Source File: ReporterPluginServiceImpl.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
public Maybe<ReporterPlugin> findById(String reporterId) {
    LOGGER.debug("Find reporter plugin by ID: {}", reporterId);
    return Maybe.create(emitter -> {
        try {
            Plugin reporter = reporterPluginManager.findById(reporterId);
            if (reporter != null) {
                emitter.onSuccess(convert(reporter));
            } else {
                emitter.onComplete();
            }
        } catch (Exception ex) {
            LOGGER.error("An error occurs while trying to get reporter plugin : {}", reporterId, ex);
            emitter.onError(new TechnicalManagementException("An error occurs while trying to get reporter plugin : " + reporterId, ex));
        }
    });
}
 
Example 8
Source File: ExtensionGrantPluginServiceImpl.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
public Maybe<ExtensionGrantPlugin> findById(String extensionGrantPluginId) {
    LOGGER.debug("Find extension grant plugin by ID: {}", extensionGrantPluginId);
    return Maybe.create(emitter -> {
        try {
            Plugin extensionGrant = extensionGrantPluginManager.findById(extensionGrantPluginId);
            if (extensionGrant != null) {
                emitter.onSuccess(convert(extensionGrant));
            } else {
                emitter.onComplete();
            }
        } catch (Exception ex) {
            LOGGER.error("An error occurs while trying to get extension grant plugin : {}", extensionGrantPluginId, ex);
            emitter.onError(new TechnicalManagementException("An error occurs while trying to get extension grant plugin : " + extensionGrantPluginId, ex));
        }
    });
}
 
Example 9
Source File: PolicyPluginServiceImpl.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
public Maybe<String> getSchema(String policyId) {
    LOGGER.debug("Find policy plugin schema by ID: {}", policyId);
    return Maybe.create(emitter -> {
        try {
            String schema = policyPluginManager.getSchema(policyId);
            if (schema != null) {
                emitter.onSuccess(schema);
            } else {
                emitter.onComplete();
            }
        } catch (Exception e) {
            LOGGER.error("An error occurs while trying to get schema for policy plugin {}", policyId, e);
            emitter.onError(new TechnicalManagementException("An error occurs while trying to get schema for policy plugin " + policyId, e));
        }
    });
}
 
Example 10
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<T>}, create a JavaRX {@link Maybe<T>} that
 * produces the value passed to the MaybeConsumer, or onComplete if the value is null
 *
 * <p>Example:
 *
 * <pre>
 *     // log the name of the experiment with a given id
 *     DataController dc = getDataController();
 *     MaybeConsumers.MaybeConsumers.buildMaybe(mc -> dc.getLastUsedUnarchivedExperiment(mc))
 *                   .subscribe(experiment -> log("Name: " + experiment.getName()));
 * </pre>
 */
public static <T> Maybe<T> buildMaybe(io.reactivex.functions.Consumer<MaybeConsumer<T>> c) {
  return Maybe.create(
      emitter ->
          c.accept(
              new MaybeConsumer<T>() {
                @Override
                public void success(T value) {
                  if (value == null) {
                    emitter.onComplete();
                  } else {
                    emitter.onSuccess(value);
                  }
                }

                @Override
                public void fail(Exception e) {
                  emitter.onError(e);
                }
              }));
}
 
Example 11
Source File: CertificateServiceImpl.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
// TODO : refactor (after JWKS information)
public Maybe<CertificateProvider> getCertificateProvider(String certificateId) {
    return Maybe.create(emitter -> {
        try {
            CertificateProvider certificateProvider = this.certificateProviders.get(certificateId);
            if (certificateProvider != null) {
                emitter.onSuccess(certificateProvider);
            } else {
                emitter.onComplete();
            }
        } catch (Exception e) {
            emitter.onError(e);
        }
    });
}
 
Example 12
Source File: ToMaybe.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@Override
public Maybe<T> apply(Multi<T> multi) {
    return Maybe.create(emitter -> {
        multi.subscribe().with(
                item -> {
                    emitter.onSuccess(item);
                    emitter.onComplete();
                },
                emitter::onError,
                emitter::onComplete);
    });
}
 
Example 13
Source File: RxJavaUtils.java    From storio with Apache License 2.0 5 votes vote down vote up
@CheckResult
@NonNull
public static <Result, WrappedResult, Data> Maybe<Result> createMaybe(
        @NonNull StorIOContentResolver storIOContentResolver,
        @NonNull PreparedMaybeOperation<Result, WrappedResult, Data> operation
) {
    throwExceptionIfRxJava2IsNotAvailable("asRxMaybe()");

    final Maybe<Result> maybe =
            Maybe.create(new MaybeOnSubscribeExecuteAsBlocking<Result, WrappedResult, Data>(operation));

    return subscribeOn(storIOContentResolver, maybe);
}
 
Example 14
Source File: RxJavaUtils.java    From storio with Apache License 2.0 5 votes vote down vote up
@CheckResult
@NonNull
public static <Result, WrappedResult, Data> Maybe<Result> createMaybe(
    @NonNull StorIOSQLite storIOSQLite,
    @NonNull PreparedMaybeOperation<Result, WrappedResult, Data> operation
) {
    throwExceptionIfRxJava2IsNotAvailable("asRxMaybe()");

    final Maybe<Result> maybe =
        Maybe.create(new MaybeOnSubscribeExecuteAsBlocking<Result, WrappedResult, Data>(operation));

    return subscribeOn(storIOSQLite, maybe);
}
 
Example 15
Source File: RequestContextAssemblyTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static Maybe<String> maybe(String input) {
    RequestContext.current();
    return Maybe.create(emitter -> {
        RequestContext.current();
        emitter.onSuccess(input);
    });
}
 
Example 16
Source File: LoadDirSettingsObservable.java    From edslite with GNU General Public License v2.0 5 votes vote down vote up
public static Maybe<DirectorySettings> create(Location targetLocation)
{
    return Maybe.create(s -> {
        Path p = targetLocation.getCurrentPath();
        if(p.isFile())
            p = p.getParentPath();
        DirectorySettings ds = getDirectorySettings(p);
        if(ds == null)
            s.onComplete();
        else
            s.onSuccess(ds);
    });
}
 
Example 17
Source File: InAppMessageStreamManager.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
private static <T> Maybe<T> taskToMaybe(Task<T> task) {
  return Maybe.create(
      emitter -> {
        task.addOnSuccessListener(
            result -> {
              emitter.onSuccess(result);
              emitter.onComplete();
            });
        task.addOnFailureListener(
            e -> {
              emitter.onError(e);
              emitter.onComplete();
            });
      });
}
 
Example 18
Source File: ElasticClientAdapter.java    From micronaut-microservices-poc with Apache License 2.0 5 votes vote down vote up
public Maybe<SearchResponse> search(SearchRequest searchRequest) {
    return Maybe.create(sink ->
            restHighLevelClient.searchAsync(searchRequest, new ActionListener<SearchResponse>() {
                @Override
                public void onResponse(SearchResponse searchResponse) {
                    sink.onSuccess(searchResponse);
                }

                @Override
                public void onFailure(Exception e) {
                    sink.onError(e);
                }
            }));
}
 
Example 19
Source File: FusedLocation.java    From RxGps with Apache License 2.0 4 votes vote down vote up
@RequiresPermission(anyOf = {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION})
public Maybe<Location> lastLocation() {
    return Maybe.create(new LocationLastMaybeOnSubscribe(rxLocation));
}
 
Example 20
Source File: MaybeOnSubscribeExecuteAsBlockingTest.java    From storio with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("CheckResult")
@Test
public void shouldCallOnErrorIfExceptionOccurred() {
    //noinspection unchecked
    final PreparedMaybeOperation<Object, Object, Object> preparedOperation = mock(PreparedMaybeOperation.class);

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

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

    TestObserver<Object> testObserver = new TestObserver<Object>();

    Maybe<Object> maybe = Maybe.create(new MaybeOnSubscribeExecuteAsBlocking<Object, Object, Object>(preparedOperation));

    verifyZeroInteractions(preparedOperation);

    maybe.subscribe(testObserver);

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

    verify(preparedOperation).executeAsBlocking();
}