io.reactivex.rxjava3.core.Completable Java Examples

The following examples show how to use io.reactivex.rxjava3.core.Completable. 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: Transformers.java    From mobius with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an {@link ObservableTransformer} that will flatten the provided {@link Consumer} into
 * the stream as a {@link Completable} every time it receives an effect from the upstream effects
 * observable. This will result in calling the consumer on the specified scheduler, and passing it
 * the requested effect object.
 *
 * @param doEffect the {@link Consumer} to be run every time the effect is requested
 * @param scheduler the {@link Scheduler} to be used when invoking the consumer
 * @param <F> the type of Effect this transformer handles
 * @param <E> these transformers are for effects that do not result in any events; however, they
 *     still need to share the same Event type
 * @return an {@link ObservableTransformer} that can be used with a {@link
 *     RxMobius.SubtypeEffectHandlerBuilder}.
 */
static <F, E> ObservableTransformer<F, E> fromConsumer(
    final Consumer<F> doEffect, @Nullable final Scheduler scheduler) {
  return new ObservableTransformer<F, E>() {
    @Override
    public ObservableSource<E> apply(Observable<F> effectStream) {
      return effectStream
          .flatMapCompletable(
              new Function<F, CompletableSource>() {
                @Override
                public CompletableSource apply(final F effect) {
                  Completable completable =
                      Completable.fromAction(
                          new Action() {
                            @Override
                            public void run() throws Throwable {
                              doEffect.accept(effect);
                            }
                          });
                  return scheduler == null ? completable : completable.subscribeOn(scheduler);
                }
              })
          .toObservable();
    }
  };
}
 
Example #2
Source File: TimeLimiterTransformerCompletableTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void doNotTimeout() {
    given(helloWorldService.returnHelloWorld())
        .willReturn("hello");
    given(timeLimiter.getTimeLimiterConfig())
        .willReturn(toConfig(Duration.ofMinutes(1)));
    TestObserver<?> observer = Completable.fromRunnable(helloWorldService::returnHelloWorld)
        .compose(TimeLimiterTransformer.of(timeLimiter))
        .test();

    testScheduler.advanceTimeBy(1, TimeUnit.MINUTES);

    observer.assertComplete();
    then(timeLimiter).should()
        .onSuccess();
}
 
Example #3
Source File: RestGuild.java    From catnip with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Nonnull
public Completable removeGuildBan(@Nonnull final String guildId, @Nonnull final String userId,
                                  @Nullable final String reason) {
    return Completable.fromObservable(catnip().requester()
            .queue(new OutboundRequest(Routes.REMOVE_GUILD_BAN.withMajorParam(guildId),
                    Map.of("user", userId)).reason(reason).emptyBody(true)));
}
 
Example #4
Source File: RestChannel.java    From catnip with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Nonnull
public Completable editPermissionOverride(@Nonnull final String channelId, @Nonnull final String overwriteId,
                                          @Nonnull final Collection<Permission> allowed,
                                          @Nonnull final Collection<Permission> denied,
                                          final boolean isMember, @Nullable final String reason) {
    return Completable.fromObservable(catnip().requester()
            .queue(new OutboundRequest(Routes.EDIT_CHANNEL_PERMISSIONS.withMajorParam(channelId),
                    Map.of("overwrite", overwriteId), JsonObject.builder()
                    .value("allow", Permission.from(allowed))
                    .value("deny", Permission.from(denied))
                    .value("type", isMember ? "member" : "role")
                    .done(),
                    reason
            )));
}
 
Example #5
Source File: PetApi.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Add a new pet to the store
 * 
 * @param body Pet object that needs to be added to the store (required)
 * @return Completable
 */
@Headers({
  "Content-Type:application/json"
})
@POST("pet")
Completable addPet(
  @retrofit2.http.Body Pet body
);
 
Example #6
Source File: RestGuild.java    From catnip with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Nonnull
@CheckReturnValue
public Completable deleteGuildRole(@Nonnull final String guildId, @Nonnull final String roleId,
                                   @Nullable final String reason) {
    return Completable.fromObservable(catnip().requester()
            .queue(new OutboundRequest(Routes.DELETE_GUILD_ROLE.withMajorParam(guildId),
                    Map.of("role", roleId)).reason(reason).emptyBody(true)));
}
 
Example #7
Source File: PetApi.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Update an existing pet
 * 
 * @param body Pet object that needs to be added to the store (required)
 * @return Completable
 */
@Headers({
  "Content-Type:application/json"
})
@PUT("pet")
Completable updatePet(
  @retrofit2.http.Body Pet body
);
 
Example #8
Source File: SingleRateLimiter.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Override
protected void subscribeActual(SingleObserver<? super T> downstream) {
    long waitDuration = rateLimiter.reservePermission();
    if (waitDuration >= 0) {
        if (waitDuration > 0) {
            Completable.timer(waitDuration, TimeUnit.NANOSECONDS)
                .subscribe(() -> upstream.subscribe(new RateLimiterSingleObserver(downstream)));
        } else {
            upstream.subscribe(new RateLimiterSingleObserver(downstream));
        }
    } else {
        downstream.onSubscribe(EmptyDisposable.INSTANCE);
        downstream.onError(RequestNotPermitted.createRequestNotPermitted(rateLimiter));
    }
}
 
Example #9
Source File: RestEmoji.java    From catnip with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Nonnull
public Completable deleteGuildEmoji(@Nonnull final String guildId, @Nonnull final String emojiId,
                                    @Nullable final String reason) {
    return Completable.fromObservable(catnip().requester().queue(
            new OutboundRequest(
                    Routes.DELETE_GUILD_EMOJI.withMajorParam(guildId),
                    Map.of("emojis", emojiId)).reason(reason).emptyBody(true)));
}
 
Example #10
Source File: RestGuild.java    From catnip with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Nonnull
@CheckReturnValue
public Completable modifyGuildChannelPositions(@Nonnull final PositionUpdater updater,
                                               @Nullable final String reason) {
    final JsonArray array = new JsonArray();
    updater.entries()
            .stream()
            .map(x -> JsonObject.builder().value("id", x.getKey()).value("position", x.getValue()).done())
            .forEach(array::add);
    return Completable.fromObservable(catnip().requester()
            .queue(new OutboundRequest(Routes.MODIFY_GUILD_CHANNEL_POSITIONS.withMajorParam(updater.guildId()),
                    Map.of(), array, reason)));
}
 
Example #11
Source File: FakeApi.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * creates an XmlItem
 * this route creates an XmlItem
 * @param xmlItem XmlItem Body (required)
 * @return Completable
 */
@Headers({
  "Content-Type:application/xml"
})
@POST("fake/create_xml_item")
Completable createXmlItem(
  @retrofit2.http.Body XmlItem xmlItem
);
 
Example #12
Source File: CompletableBulkheadTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldComplete() {
    given(bulkhead.tryAcquirePermission()).willReturn(true);

    Completable.complete()
        .compose(BulkheadOperator.of(bulkhead))
        .test()
        .assertComplete();

    then(bulkhead).should().onComplete();
}
 
Example #13
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 #14
Source File: MessageChannel.java    From catnip with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Add a reaction to the message with the given id in this channel.
 *
 * @param messageId The id of the message to add a reaction to.
 * @param emoji     The reaction to add.
 *
 * @return A Observable that completes when the reaction is added.
 */
@Nonnull
default Completable addReaction(@Nonnull final String messageId, @Nonnull final String emoji) {
    if(isGuild()) {
        PermissionUtil.checkPermissions(catnip(), asGuildChannel().guildId(), id(),
                Permission.ADD_REACTIONS, Permission.READ_MESSAGE_HISTORY);
    }
    return catnip().rest().channel().addReaction(id(), messageId, emoji);
}
 
Example #15
Source File: MessageChannel.java    From catnip with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Add a reaction to the message with the given id in this channel.
 *
 * @param messageId The id of the message to add a reaction to.
 * @param emoji     The reaction to add.
 *
 * @return A Observable that completes when the reaction is added.
 */
@Nonnull
default Completable addReaction(@Nonnull final String messageId, @Nonnull final Emoji emoji) {
    if(isGuild()) {
        PermissionUtil.checkPermissions(catnip(), asGuildChannel().guildId(), id(),
                Permission.ADD_REACTIONS, Permission.READ_MESSAGE_HISTORY);
    }
    return catnip().rest().channel().addReaction(id(), messageId, emoji);
}
 
Example #16
Source File: MessageChannel.java    From catnip with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Delete a user's reaction on the given message.
 *
 * @param messageId The id of the message to remove a reaction from.
 * @param userId    The id of the user whose reaction is to be removed.
 * @param emoji     The reaction to remove.
 *
 * @return A Observable that completes when the reaction is removed.
 */
@Nonnull
default Completable deleteUserReaction(@Nonnull final String messageId, @Nonnull final String userId,
                                       @Nonnull final String emoji) {
    if(isGuild()) {
        PermissionUtil.checkPermissions(catnip(), asGuildChannel().guildId(), id(),
                Permission.MANAGE_MESSAGES);
    }
    return catnip().rest().channel().deleteUserReaction(id(), messageId, userId, emoji);
}
 
Example #17
Source File: MessageChannel.java    From catnip with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Delete all reactions on the given message
 *
 * @param messageId The id of the message to remove all reactions from.
 *
 * @return A Observable that completes when the reaction is removed.
 */
@Nonnull
default Completable bulkRemoveReaction(@Nonnull final String messageId) {
    if(isGuild()) {
        PermissionUtil.checkPermissions(catnip(), asGuildChannel().guildId(), id(),
                Permission.MANAGE_MESSAGES);
    }
    return catnip().rest().channel().deleteAllReactions(id(), messageId);
}
 
Example #18
Source File: Webhook.java    From catnip with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Deletes the webhook.
 *
 * @return A Single that completes when the webhook is deleted.
 */
@Nonnull
@CheckReturnValue
default Completable delete() {
    PermissionUtil.checkPermissions(catnip(), guildId(), channelId(), Permission.MANAGE_WEBHOOKS);
    return catnip().rest().webhook().deleteWebhook(id());
}
 
Example #19
Source File: Message.java    From catnip with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Nonnull
default Completable delete(@Nullable final String reason) {
    final User self = catnip().selfUser();
    if(self != null && !author().id().equals(self.id())) {
        PermissionUtil.checkPermissions(catnip(), guildId(), channelId(),
                Permission.MANAGE_MESSAGES);
    }
    return catnip().rest().channel().deleteMessage(channelId(), id(), reason);
}
 
Example #20
Source File: CachingBuffer.java    From catnip with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private Completable maybeCache(final String eventType, final int shardId, final JsonObject data) {
    if(CACHE_EVENTS.contains(eventType)) {
        try {
            return catnip().cacheWorker().updateCache(eventType, shardId, data);
        } catch(final Exception e) {
            catnip().logAdapter().warn("Got error updating cache for payload {}", eventType, e);
            catnip().logAdapter().warn("Payload: {}", JsonUtil.encodePrettily(data));
            return RxHelpers.completedCompletable(catnip());
        }
    } else {
        return RxHelpers.completedCompletable(catnip());
    }
}
 
Example #21
Source File: CompletableRateLimiterTest.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());

    Completable.complete()
        .compose(RateLimiterOperator.of(rateLimiter))
        .test()
        .awaitDone(1, TimeUnit.SECONDS);
}
 
Example #22
Source File: RestGuild.java    From catnip with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Nonnull
public Completable addGuildMemberRole(@Nonnull final String guildId, @Nonnull final String userId,
                                      @Nonnull final String roleId, @Nullable final String reason) {
    return Completable.fromObservable(catnip().requester()
            .queue(new OutboundRequest(Routes.ADD_GUILD_MEMBER_ROLE.withMajorParam(guildId),
                    Map.of("user", userId, "role", roleId)).reason(reason).emptyBody(true)));
}
 
Example #23
Source File: RestChannel.java    From catnip with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Nonnull
public Completable deleteMessage(@Nonnull final String channelId, @Nonnull final String messageId,
                                 @Nullable final String reason) {
    return catnip().requester().queue(new OutboundRequest(Routes.DELETE_MESSAGE.withMajorParam(channelId),
            Map.of("message", messageId)).reason(reason))
            .ignoreElements();
}
 
Example #24
Source File: RestChannel.java    From catnip with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Nonnull
public Completable editPermissionOverride(@Nonnull final String channelId, @Nonnull final PermissionOverride overwrite,
                                          @Nonnull final Collection<Permission> allowed,
                                          @Nonnull final Collection<Permission> denied,
                                          @Nullable final String reason) {
    return editPermissionOverride(channelId,
            overwrite.id(),
            allowed,
            denied,
            overwrite.type() == OverrideType.MEMBER,
            reason
    );
}
 
Example #25
Source File: RestChannel.java    From catnip with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Nonnull
public Completable addReaction(@Nonnull final String channelId, @Nonnull final String messageId,
                               @Nonnull final String emoji) {
    return catnip().requester().queue(new OutboundRequest(Routes.CREATE_REACTION.withMajorParam(channelId),
            Map.of("message", messageId, "emojis", encodeUTF8(emoji)), new JsonObject()))
            .ignoreElements();
}
 
Example #26
Source File: FlowableRateLimiter.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Override
protected void subscribeActual(Subscriber<? super T> downstream) {
    long waitDuration = rateLimiter.reservePermission();
    if (waitDuration >= 0) {
        if (waitDuration > 0) {
            Completable.timer(waitDuration, TimeUnit.NANOSECONDS)
                .subscribe(() -> upstream.subscribe(new RateLimiterSubscriber(downstream)));
        } else {
            upstream.subscribe(new RateLimiterSubscriber(downstream));
        }
    } else {
        downstream.onSubscribe(EmptySubscription.INSTANCE);
        downstream.onError(createRequestNotPermitted(rateLimiter));
    }
}
 
Example #27
Source File: RestChannel.java    From catnip with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Nonnull
public Completable editPermissionOverride(@Nonnull final String channelId, @Nonnull final String overwriteId,
                                          @Nonnull final Collection<Permission> allowed,
                                          @Nonnull final Collection<Permission> denied,
                                          final boolean isMember) {
    return editPermissionOverride(channelId, overwriteId, allowed, denied, isMember, null);
}
 
Example #28
Source File: RestChannel.java    From catnip with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Nonnull
public Completable deleteEmojiReaction(@Nonnull final String channelId, @Nonnull final String messageId,
                                     @Nonnull final String emoji) {
    return Completable.fromObservable(catnip().requester()
            .queue(new OutboundRequest(Routes.DELETE_EMOJI_REACTIONS.withMajorParam(channelId),
                    Map.of("message", messageId, "emojis", encodeUTF8(emoji))).emptyBody(true)));
}
 
Example #29
Source File: CompletableRateLimiterTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldEmitCompleted() {
    given(rateLimiter.reservePermission()).willReturn(Duration.ofSeconds(0).toNanos());

    Completable.complete()
        .compose(RateLimiterOperator.of(rateLimiter))
        .test()
        .assertComplete();
}
 
Example #30
Source File: RestChannel.java    From catnip with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Nonnull
public Completable deletePermissionOverride(@Nonnull final String channelId,
                                            @Nonnull final String overwriteId, @Nullable final String reason) {
    return Completable.fromObservable(catnip().requester()
            .queue(new OutboundRequest(Routes.DELETE_CHANNEL_PERMISSION.withMajorParam(channelId),
                    Map.of("overwrite", overwriteId)).reason(reason).emptyBody(true)));
}