io.reactivex.rxjava3.core.Single Java Examples

The following examples show how to use io.reactivex.rxjava3.core.Single. 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: UntilEventTransformerSingleTest.java    From RxLifecycle with Apache License 2.0 6 votes vote down vote up
@Test
public void twoEvents() {
    TestObserver<String> testObserver = Single.just("1")
        .delay(1, TimeUnit.MILLISECONDS, testScheduler)
        .compose(RxLifecycle.<String, String>bindUntilEvent(lifecycle, "stop"))
        .test();

    lifecycle.onNext("keep going");
    testObserver.assertNoErrors();

    lifecycle.onNext("stop");
    testScheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS);

    testObserver.assertNoValues();
    testObserver.assertError(CancellationException.class);
}
 
Example #2
Source File: CatnipImpl.java    From catnip with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Nonnull
@Override
public Single<GatewayInfo> fetchGatewayInfo() {
    return rest.user().getGatewayBot()
            .map(g -> {
                if(g.valid()) {
                    gatewayInfo.set(g);
                    return g;
                } else {
                    throw new RuntimeException("Gateway info not valid! Is your token valid?");
                }
            })
            .doOnError(e -> {
                throw new RuntimeException(e);
            });
}
 
Example #3
Source File: UntilLifecycleTransformerSingleTest.java    From RxLifecycle with Apache License 2.0 6 votes vote down vote up
@Test
public void oneEvent() {
    TestObserver<String> testObserver = Single.just("1")
        .delay(1, TimeUnit.MILLISECONDS, testScheduler)
        .compose(RxLifecycle.<String, String>bind(lifecycle))
        .test();

    testObserver.assertNoValues();
    testObserver.assertNoErrors();

    lifecycle.onNext("stop");
    testScheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS);

    testObserver.assertNoValues();
    testObserver.assertError(CancellationException.class);
}
 
Example #4
Source File: SingleCircuitBreakerTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSubscribeToMonoFromCallableMultipleTimes() {
    given(circuitBreaker.tryAcquirePermission()).willReturn(true);
    given(helloWorldService.returnHelloWorld()).willReturn("Hello World");

    Single.fromCallable(() -> helloWorldService.returnHelloWorld())
        .compose(CircuitBreakerOperator.of(circuitBreaker))
        .repeat(2)
        .test()
        .assertResult("Hello World", "Hello World");

    then(helloWorldService).should(times(2)).returnHelloWorld();
    then(circuitBreaker).should(times(2)).onSuccess(anyLong(), any(TimeUnit.class));
    then(circuitBreaker).should(never())
        .onError(anyLong(), any(TimeUnit.class), any(Throwable.class));
}
 
Example #5
Source File: ReactiveIOInvoker.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected AsyncResponseImpl handleSingle(Message inMessage, Single<?> single) {
    final AsyncResponseImpl asyncResponse = new AsyncResponseImpl(inMessage);
    Disposable d = single.subscribe(asyncResponse::resume, t -> handleThrowable(asyncResponse, t));
    if (d == null) {
        throw new IllegalStateException("Subscribe did not return a Disposable");
    }
    return asyncResponse;
}
 
Example #6
Source File: TimeLimiterTransformerSingleTest.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 = Single.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 #7
Source File: ReactiveBatchProcessorV2.java    From code-examples with MIT License 5 votes vote down vote up
public void start() {
  // WARNING: this code doesn't work as expected
  messageSource.getMessageBatches()
      .subscribeOn(Schedulers.from(Executors.newSingleThreadExecutor()))
      .doOnNext(batch -> logger.log(batch.toString()))
      .flatMap(batch -> Flowable.fromIterable(batch.getMessages()))
      .flatMapSingle(m -> Single.defer(() -> Single.just(messageHandler.handleMessage(m)))
          .subscribeOn(threadPoolScheduler(threads, threadPoolQueueSize)))
      .subscribeWith(new SimpleSubscriber<>(threads, 1));
}
 
Example #8
Source File: ReactiveBatchProcessorV3.java    From code-examples with MIT License 5 votes vote down vote up
public void start() {
  // WARNING: this code doesn't work as expected
  Scheduler scheduler = threadPoolScheduler(threads, threadPoolQueueSize);

  messageSource.getMessageBatches()
      .subscribeOn(Schedulers.from(Executors.newSingleThreadExecutor()))
      .doOnNext(batch -> logger.log(batch.toString()))
      .flatMap(batch -> Flowable.fromIterable(batch.getMessages()))
      .flatMapSingle(m -> Single.defer(() -> Single.just(messageHandler.handleMessage(m)))
          .subscribeOn(scheduler))
      .subscribeWith(new SimpleSubscriber<>(threads, 1));
}
 
Example #9
Source File: MemoryEntityCache.java    From catnip with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected <I, T> Single<T> or(final I id, final T data) {
    if(data == null) {
        return Single.error(new IllegalArgumentException("No entity for: " + id));
    } else {
        return Single.just(data);
    }
}
 
Example #10
Source File: GuildChannel.java    From catnip with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Nonnull
public Single<GuildChannel> submit() {
    if(channel == null) {
        throw new IllegalStateException("Cannot submit edit without a channel object! Please use RestChannel directly instead");
    }
    return channel.catnip().rest().channel().modifyChannel(channel.id(), this, null);
}
 
Example #11
Source File: RxQuery.java    From objectbox-java with Apache License 2.0 5 votes vote down vote up
/**
 * The returned Single emits one Query result as a List.
 */
public static <T> Single<List<T>> single(final Query<T> query) {
    return Single.create(emitter -> {
        query.subscribe().single().observer(data -> {
            if (!emitter.isDisposed()) {
                emitter.onSuccess(data);
            }
        });
        // no need to cancel, single never subscribes
    });
}
 
Example #12
Source File: MessageChannel.java    From catnip with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Send a message to this channel with the specified content.
 *
 * @param content The text content to send.
 *
 * @return A Observable that completes when the message is sent.
 */
@Nonnull
default Single<Message> sendMessage(@Nonnull final String content) {
    if(isGuild()) {
        PermissionUtil.checkPermissions(catnip(), asGuildChannel().guildId(), id(),
                Permission.SEND_MESSAGES);
    }
    final Single<Message> future = catnip().rest().channel().sendMessage(id(), content);
    // Inject guild manually because Discord does not send it in response
    if(isGuild()) {
        return future.map(msg -> ((MessageImpl) msg).guildIdAsLong(asGuildChannel().guildIdAsLong()));
    }
    return future;
}
 
Example #13
Source File: GuildChannel.java    From catnip with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Nonnull
public Single<GuildChannel> submit(@Nullable final String reason) {
    if(channel == null) {
        throw new IllegalStateException("Cannot submit edit without a channel object! Please use RestChannel directly instead");
    }
    return channel.catnip().rest().channel().modifyChannel(channel.id(), this, reason);
}
 
Example #14
Source File: UntilCorrespondingEventTransformerSingleTest.java    From RxLifecycle with Apache License 2.0 5 votes vote down vote up
@Test
public void twoOpenEvents() {
    TestObserver<String> testObserver = Single.just("1")
        .delay(1, TimeUnit.MILLISECONDS, testScheduler)
        .compose(RxLifecycle.<String, String>bind(lifecycle, CORRESPONDING_EVENTS))
        .test();

    testObserver.assertNoValues();

    lifecycle.onNext("create");
    lifecycle.onNext("start");
    testScheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS);
    testObserver.assertValue("1");
    testObserver.assertComplete();
}
 
Example #15
Source File: SingleRateLimiterTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldEmitErrorWithRequestNotPermittedException() {
    given(rateLimiter.reservePermission()).willReturn(-1L);

    Single.just(1)
        .compose(RateLimiterOperator.of(rateLimiter))
        .test()
        .assertError(RequestNotPermitted.class)
        .assertNotComplete();
}
 
Example #16
Source File: RemoteLndLightningService.java    From zap-android with MIT License 4 votes vote down vote up
@Override
public Single<com.github.lightningnetwork.lnd.lnrpc.NewAddressResponse> newAddress(com.github.lightningnetwork.lnd.lnrpc.NewAddressRequest request) {
    return DefaultSingle.createDefault(emitter -> asyncStub.newAddress(request, new RemoteLndSingleObserver<>(emitter)));
}
 
Example #17
Source File: RestChannel.java    From catnip with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Nonnull
@CheckReturnValue
public Single<Channel> deleteChannel(@Nonnull final String channelId) {
    return deleteChannel(channelId, null);
}
 
Example #18
Source File: RemoteLndLightningService.java    From zap-android with MIT License 4 votes vote down vote up
@Override
public Single<com.github.lightningnetwork.lnd.lnrpc.ClosedChannelsResponse> closedChannels(com.github.lightningnetwork.lnd.lnrpc.ClosedChannelsRequest request) {
    return DefaultSingle.createDefault(emitter -> asyncStub.closedChannels(request, new RemoteLndSingleObserver<>(emitter)));
}
 
Example #19
Source File: RemoteLndLightningService.java    From zap-android with MIT License 4 votes vote down vote up
@Override
public Single<com.github.lightningnetwork.lnd.lnrpc.ListUnspentResponse> listUnspent(com.github.lightningnetwork.lnd.lnrpc.ListUnspentRequest request) {
    return DefaultSingle.createDefault(emitter -> asyncStub.listUnspent(request, new RemoteLndSingleObserver<>(emitter)));
}
 
Example #20
Source File: MemoryEntityCache.java    From catnip with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Nonnull
@Override
public Single<UserDMChannel> dmChannelAsync(final long id) {
    return or(id, dmChannel(id));
}
 
Example #21
Source File: RestUser.java    From catnip with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Nonnull
@CheckReturnValue
public Single<GatewayInfo> getGatewayBot() {
    return Single.fromObservable(getGatewayBotRaw().map(e -> entityBuilder().createGatewayInfo(e)));
}
 
Example #22
Source File: RemoteLndLightningService.java    From zap-android with MIT License 4 votes vote down vote up
@Override
public Single<com.github.lightningnetwork.lnd.lnrpc.WalletBalanceResponse> walletBalance(com.github.lightningnetwork.lnd.lnrpc.WalletBalanceRequest request) {
    return DefaultSingle.createDefault(emitter -> asyncStub.walletBalance(request, new RemoteLndSingleObserver<>(emitter)));
}
 
Example #23
Source File: CustomizableEntityCache.java    From catnip with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Nonnull
@Override
public Single<Role> roleAsync(final long guildId, final long id) {
    return Single.error(new IllegalArgumentException("No entity with id " + id));
}
 
Example #24
Source File: RemoteLndLightningService.java    From zap-android with MIT License 4 votes vote down vote up
@Override
public Single<com.github.lightningnetwork.lnd.lnrpc.GetInfoResponse> getInfo(com.github.lightningnetwork.lnd.lnrpc.GetInfoRequest request) {
    return DefaultSingle.createDefault(emitter -> asyncStub.getInfo(request, new RemoteLndSingleObserver<>(emitter)));
}
 
Example #25
Source File: RestWebhook.java    From catnip with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Nonnull
@CheckReturnValue
public Single<Webhook> getWebhookToken(@Nonnull final String webhookId, @Nonnull final String token) {
    return Single.fromObservable(getWebhookTokenRaw(webhookId, token).map(entityBuilder()::createWebhook));
}
 
Example #26
Source File: RemoteLndWalletUnlockerService.java    From zap-android with MIT License 4 votes vote down vote up
@Override
public Single<com.github.lightningnetwork.lnd.lnrpc.GenSeedResponse> genSeed(com.github.lightningnetwork.lnd.lnrpc.GenSeedRequest request) {
    return DefaultSingle.createDefault(emitter -> asyncStub.genSeed(request, new RemoteLndSingleObserver<>(emitter)));
}
 
Example #27
Source File: CatnipShard.java    From catnip with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Nonnull
@CheckReturnValue
Single<ShardConnectState> connect();
 
Example #28
Source File: RemoteLndLightningService.java    From zap-android with MIT License 4 votes vote down vote up
@Override
public Single<com.github.lightningnetwork.lnd.lnrpc.PendingChannelsResponse> pendingChannels(com.github.lightningnetwork.lnd.lnrpc.PendingChannelsRequest request) {
    return DefaultSingle.createDefault(emitter -> asyncStub.pendingChannels(request, new RemoteLndSingleObserver<>(emitter)));
}
 
Example #29
Source File: RestChannel.java    From catnip with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Nonnull
public Single<Message> editMessage(@Nonnull final String channelId, @Nonnull final String messageId,
                                   @Nonnull final MessageOptions message, @Nonnull final Set<MessageFlag> flags) {
    return Single.fromObservable(editMessageRaw(channelId, messageId, message, flags)
            .map(entityBuilder()::createMessage));
}
 
Example #30
Source File: MemoryEntityCache.java    From catnip with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Nonnull
@Override
public Single<Presence> presenceAsync(final long id) {
    return or(id, presence(id), DEFAULT_PRESENCE);
}