io.reactivex.rxjava3.core.Maybe Java Examples

The following examples show how to use io.reactivex.rxjava3.core.Maybe. 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: CacheFirstTimeoutStrategy.java    From RxCache with Apache License 2.0 6 votes vote down vote up
@Override
public <T> Maybe<Record<T>> execute(RxCache rxCache, String key, Maybe<T> source, Type type) {

    Maybe<Record<T>> cache = rxCache.<T>load2Maybe(key, type)
            .filter(new Predicate<Record<T>>() {
                @Override
                public boolean test(Record<T> record) throws Exception {
                    return System.currentTimeMillis() - record.getCreateTime() <= timestamp;
                }
            });

    Maybe<Record<T>> remote = source
            .map(new Function<T, Record<T>>() {
                @Override
                public Record<T> apply(@NonNull T t) throws Exception {

                    rxCache.save(key, t);

                    return new Record<>(Source.CLOUD, key, t);
                }
            });

    return cache.switchIfEmpty(remote);
}
 
Example #2
Source File: RemoteOnlyStrategy.java    From RxCache with Apache License 2.0 6 votes vote down vote up
@Override
public <T> Maybe<Record<T>> execute(RxCache rxCache, String key, Maybe<T> source, Type type) {

    Maybe<Record<T>> remote = source
            .map(new Function<T, Record<T>>() {
                @Override
                public Record<T> apply(@NonNull T t) throws Exception {

                    rxCache.save(key, t);

                    return new Record<>(Source.CLOUD, key, t);
                }
            });

    return remote;
}
 
Example #3
Source File: CacheFirstStrategy.java    From RxCache with Apache License 2.0 6 votes vote down vote up
@Override
public <T> Maybe<Record<T>> execute(RxCache rxCache, String key, Maybe<T> source, Type type) {

    Maybe<Record<T>> cache = rxCache.<T>load2Maybe(key, type);

    Maybe<Record<T>> remote = source
            .map(new Function<T, Record<T>>() {
                @Override
                public Record<T> apply(@NonNull T t) throws Exception {

                    rxCache.save(key, t);

                    return new Record<>(Source.CLOUD, key, t);
                }
            });

    return cache.switchIfEmpty(remote);
}
 
Example #4
Source File: DataServiceTest.java    From java-11-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void testMaybe() throws InterruptedException {
    DataService dataService = new DataServiceImpl(executor);
    Maybe<DataItem> maybe = dataService.getMaybe(new SingleDataQuery("maybe-query"));
    SynchronousMaybeObserver maybeObserver = new SynchronousMaybeObserver();

    maybe.subscribe(maybeObserver);
    maybeObserver.await(10, TimeUnit.SECONDS);

    Assert.assertTrue(maybeObserver.isCompleted());
    Assert.assertFalse(maybeObserver.hasErrors());
    Assert.assertNotNull(maybeObserver.getDataItem());
    Assert.assertEquals(maybeObserver.getDataItem().getRequest(), "maybe-query");
    Assert.assertEquals(maybeObserver.getDataItem().getResult(), "maybe-data-result");
    Assert.assertTrue(maybeObserver.getDataItem().getOrdinal() == 1);
}
 
Example #5
Source File: RemoteFirstStrategy.java    From RxCache with Apache License 2.0 6 votes vote down vote up
@Override
public <T> Maybe<Record<T>> execute(RxCache rxCache, String key, Maybe<T> source, Type type) {

    Maybe<Record<T>> cache = rxCache.<T>load2Maybe(key, type);

    Maybe<Record<T>> remote = source
            .map(new Function<T, Record<T>>() {
                @Override
                public Record<T> apply(@NonNull T t) throws Exception {

                    rxCache.save(key, t);

                    return new Record<>(Source.CLOUD, key, t);
                }
            });

    return remote.switchIfEmpty(cache);
}
 
Example #6
Source File: CacheAndRemoteStrategy.java    From RxCache with Apache License 2.0 6 votes vote down vote up
@Override
public <T> Maybe<Record<T>> execute(RxCache rxCache, String key, Maybe<T> source, Type type) {

    Maybe<Record<T>> cache = rxCache.<T>load2Maybe(key, type);

    Maybe<Record<T>> remote = source
            .map(new Function<T, Record<T>>() {
                @Override
                public Record<T> apply(@NonNull T t) throws Exception {

                    rxCache.save(key, t);

                    return new Record<>(Source.CLOUD, key, t);
                }
            });

    return Maybe.concatDelayError(Arrays.asList(cache,remote))
            .filter(new Predicate<Record<T>>() {
                @Override
                public boolean test(@NonNull Record<T> record) throws Exception {
                    return record.getData() != null;
                }
            })
            .firstElement();
}
 
Example #7
Source File: MaybeCircuitBreakerTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSubscribeToMaybeJust() {
    given(circuitBreaker.tryAcquirePermission()).willReturn(true);

    Maybe.just(1)
        .compose(CircuitBreakerOperator.of(circuitBreaker))
        .test()
        .assertResult(1);

    then(circuitBreaker).should().onSuccess(anyLong(), any(TimeUnit.class));
    then(circuitBreaker).should(never())
        .onError(anyLong(), any(TimeUnit.class), any(Throwable.class));
}
 
Example #8
Source File: TimeLimiterTransformerMaybeTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void timeoutEmpty() {
    given(timeLimiter.getTimeLimiterConfig())
        .willReturn(toConfig(Duration.ZERO));
    TestObserver<?> observer = Maybe.empty()
        .delay(1, TimeUnit.MINUTES)
        .compose(TimeLimiterTransformer.of(timeLimiter))
        .test();

    testScheduler.advanceTimeBy(1, TimeUnit.MINUTES);

    observer.assertError(TimeoutException.class);
    then(timeLimiter).should()
        .onError(any(TimeoutException.class));
}
 
Example #9
Source File: TimeLimiterTransformerMaybeTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void otherError() {
    given(timeLimiter.getTimeLimiterConfig())
        .willReturn(toConfig(Duration.ZERO));
    TestObserver<?> observer = Maybe.error(new RuntimeException())
        .compose(TimeLimiterTransformer.of(timeLimiter))
        .test();

    testScheduler.advanceTimeBy(1, TimeUnit.MINUTES);

    observer.assertError(RuntimeException.class);
    then(timeLimiter).should()
        .onError(any(RuntimeException.class));
}
 
Example #10
Source File: Rx3UserServiceImpl.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
@Override
public Maybe<User> findById(Integer id) {
    return Maybe.fromCallable(() -> {
        User user = new User();
        user.setId(id);
        user.setNick(faker.name().name());
        user.setPhone(faker.phoneNumber().cellPhone());
        user.setEmail(faker.internet().emailAddress());
        return user;
    });
}
 
Example #11
Source File: MaybeBulkheadTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReleaseBulkheadOnlyOnce() {
    given(bulkhead.tryAcquirePermission()).willReturn(true);

    Maybe.just(Arrays.asList(1, 2, 3))
        .compose(BulkheadOperator.of(bulkhead))
        .flatMapObservable(Observable::fromIterable)
        .take(2) //this with the previous line triggers an extra dispose
        .test()
        .assertResult(1, 2);

    verify(bulkhead).onComplete();
}
 
Example #12
Source File: MaybeCircuitBreakerTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldPropagateError() {
    given(circuitBreaker.tryAcquirePermission()).willReturn(true);

    Maybe.error(new IOException("BAM!"))
        .compose(CircuitBreakerOperator.of(circuitBreaker))
        .test()
        .assertError(IOException.class)
        .assertNotComplete();

    then(circuitBreaker).should()
        .onError(anyLong(), any(TimeUnit.class), any(IOException.class));
    then(circuitBreaker).should(never()).onSuccess(anyLong(), any(TimeUnit.class));
}
 
Example #13
Source File: MaybeCircuitBreakerTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldEmitErrorWithCallNotPermittedException() {
    given(circuitBreaker.tryAcquirePermission()).willReturn(false);

    Maybe.just(1)
        .compose(CircuitBreakerOperator.of(circuitBreaker))
        .test()
        .assertError(CallNotPermittedException.class)
        .assertNotComplete();

    then(circuitBreaker).should(never()).onSuccess(anyLong(), any(TimeUnit.class));
    then(circuitBreaker).should(never())
        .onError(anyLong(), any(TimeUnit.class), any(Throwable.class));
}
 
Example #14
Source File: MaybeCircuitBreakerTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReleasePermissionOnCancel() {
    given(circuitBreaker.tryAcquirePermission()).willReturn(true);

    Maybe.just(1)
        .delay(1, TimeUnit.DAYS)
        .compose(CircuitBreakerOperator.of(circuitBreaker))
        .test()
        .dispose();

    then(circuitBreaker).should().releasePermission();
    then(circuitBreaker).should(never())
        .onError(anyLong(), any(TimeUnit.class), any(Throwable.class));
    then(circuitBreaker).should(never()).onSuccess(anyLong(), any(TimeUnit.class));
}
 
Example #15
Source File: MaybeBulkheadTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldEmitAllEvents() {
    given(bulkhead.tryAcquirePermission()).willReturn(true);

    Maybe.just(1)
        .compose(BulkheadOperator.of(bulkhead))
        .test()
        .assertResult(1);

    verify(bulkhead).onComplete();
}
 
Example #16
Source File: MaybeBulkheadTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldPropagateError() {
    given(bulkhead.tryAcquirePermission()).willReturn(true);

    Maybe.error(new IOException("BAM!"))
        .compose(BulkheadOperator.of(bulkhead))
        .test()
        .assertError(IOException.class)
        .assertNotComplete();

    verify(bulkhead).onComplete();
}
 
Example #17
Source File: MaybeBulkheadTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldEmitErrorWithBulkheadFullException() {
    given(bulkhead.tryAcquirePermission()).willReturn(false);

    Maybe.just(1)
        .compose(BulkheadOperator.of(bulkhead))
        .test()
        .assertError(BulkheadFullException.class)
        .assertNotComplete();

    verify(bulkhead, never()).onComplete();
}
 
Example #18
Source File: TimeLimiterTransformerMaybeTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void doNotTimeoutEmpty() {
    given(timeLimiter.getTimeLimiterConfig())
        .willReturn(toConfig(Duration.ofMinutes(1)));
    TestObserver<?> observer = Maybe.empty()
        .compose(TimeLimiterTransformer.of(timeLimiter))
        .test();

    observer.assertComplete();
    then(timeLimiter).should()
        .onSuccess();
}
 
Example #19
Source File: NoCacheStrategy.java    From RxCache with Apache License 2.0 5 votes vote down vote up
@Override
public <T> Maybe<Record<T>> execute(RxCache rxCache, String key, Maybe<T> source, Type type) {

    return source.map(new Function<T, Record<T>>() {
        @Override
        public Record<T> apply(@NonNull T t) throws Exception {
            return new Record<>(Source.CLOUD, key, t);
        }
    });
}
 
Example #20
Source File: TimeLimiterTransformerCompletableTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void timeout() {
    given(timeLimiter.getTimeLimiterConfig())
        .willReturn(toConfig(Duration.ZERO));
    TestObserver<?> observer = Maybe.timer(1, TimeUnit.MINUTES)
        .flatMapCompletable(t -> Completable.complete())
        .compose(TimeLimiterTransformer.of(timeLimiter))
        .test();

    testScheduler.advanceTimeBy(1, TimeUnit.MINUTES);

    observer.assertError(TimeoutException.class);
    then(timeLimiter).should()
        .onError(any(TimeoutException.class));
}
 
Example #21
Source File: MaybeRateLimiterTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldEmitEvent() {
    given(rateLimiter.reservePermission()).willReturn(Duration.ofSeconds(0).toNanos());

    Maybe.just(1)
        .compose(RateLimiterOperator.of(rateLimiter))
        .test()
        .assertResult(1);
}
 
Example #22
Source File: MaybeRateLimiterTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldDelaySubscription() {
    given(rateLimiter.reservePermission()).willReturn(Duration.ofSeconds(1).toNanos());

    Maybe.just(1)
        .compose(RateLimiterOperator.of(rateLimiter))
        .test()
        .awaitDone(2, TimeUnit.SECONDS);
}
 
Example #23
Source File: MaybeRateLimiterTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldPropagateError() {
    given(rateLimiter.reservePermission()).willReturn(Duration.ofSeconds(0).toNanos());

    Maybe.error(new IOException("BAM!"))
        .compose(RateLimiterOperator.of(rateLimiter))
        .test()
        .assertError(IOException.class)
        .assertNotComplete();
}
 
Example #24
Source File: MaybeRateLimiterTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldEmitErrorWithRequestNotPermittedException() {
    given(rateLimiter.reservePermission()).willReturn(-1L);

    Maybe.just(1)
        .compose(RateLimiterOperator.of(rateLimiter))
        .test()
        .assertError(RequestNotPermitted.class)
        .assertNotComplete();
}
 
Example #25
Source File: ObservableResponseConverterFunctionProvider.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Returns {@code true} if the specified {@link Class} can be handled by the
 * {@link ObservableResponseConverterFunction}.
 */
private static boolean isSupportedClass(Class<?> clazz) {
    return Observable.class.isAssignableFrom(clazz) ||
           Maybe.class.isAssignableFrom(clazz) ||
           Single.class.isAssignableFrom(clazz) ||
           Completable.class.isAssignableFrom(clazz);
}
 
Example #26
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 #27
Source File: LifecycleTransformer.java    From RxLifecycle with Apache License 2.0 4 votes vote down vote up
@Override
public MaybeSource<T> apply(Maybe<T> upstream) {
    return upstream.takeUntil(observable.firstElement());
}
 
Example #28
Source File: MaybeRateLimiter.java    From resilience4j with Apache License 2.0 4 votes vote down vote up
MaybeRateLimiter(Maybe<T> upstream, RateLimiter rateLimiter) {
    this.upstream = upstream;
    this.rateLimiter = rateLimiter;
}
 
Example #29
Source File: MaybeBulkhead.java    From resilience4j with Apache License 2.0 4 votes vote down vote up
MaybeBulkhead(Maybe<T> upstream, Bulkhead bulkhead) {
    this.upstream = upstream;
    this.bulkhead = bulkhead;
}
 
Example #30
Source File: MaybeCircuitBreaker.java    From resilience4j with Apache License 2.0 4 votes vote down vote up
MaybeCircuitBreaker(Maybe<T> upstream, CircuitBreaker circuitBreaker) {
    this.upstream = upstream;
    this.circuitBreaker = circuitBreaker;
}