Java Code Examples for reactor.core.publisher.Flux#usingWhen()

The following examples show how to use reactor.core.publisher.Flux#usingWhen() . 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: TestcontainersR2DBCConnectionFactoryTest.java    From testcontainers-java with MIT License 7 votes vote down vote up
@Test
public void reusesUntilConnectionFactoryIsClosed() {
    String url = "r2dbc:tc:postgresql:///db?TC_IMAGE_TAG=10-alpine";
    ConnectionFactory connectionFactory = ConnectionFactories.get(url);

    Integer updated = Flux
        .usingWhen(
            connectionFactory.create(),
            connection -> {
                return Mono
                    .from(connection.createStatement("CREATE TABLE test(id integer PRIMARY KEY)").execute())
                    .thenMany(connection.createStatement("INSERT INTO test(id) VALUES(123)").execute())
                    .flatMap(Result::getRowsUpdated);
            },
            Connection::close
        )
        .blockFirst();

    assertThat(updated).isEqualTo(1);

    Flux<Long> select = Flux
        .usingWhen(
            Flux.defer(connectionFactory::create),
            connection -> {
                return Flux
                    .from(connection.createStatement("SELECT COUNT(*) FROM test").execute())
                    .flatMap(it -> it.map((row, meta) -> (Long) row.get(0)));
            },
            Connection::close
        );

    Long rows = select.blockFirst();

    assertThat(rows).isEqualTo(1);

    close(connectionFactory);

    Assertions
        .assertThatThrownBy(select::blockFirst)
        .isInstanceOf(PostgresqlException.class)
        // relation "X" does not exists
        // https://github.com/postgres/postgres/blob/REL_10_0/src/backend/utils/errcodes.txt#L349
        .returns("42P01", e -> ((PostgresqlException) e).getErrorDetails().getCode());
}
 
Example 2
Source File: DefaultReactiveNeo4jClient.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
<T> Flux<T> doInStatementRunnerForFlux(final String targetDatabase, Function<RxQueryRunner, Flux<T>> func) {

		return Flux.usingWhen(retrieveRxStatementRunnerHolder(targetDatabase),
			holder -> func.apply(holder.getRxQueryRunner()),
			RxStatementRunnerHolder::getCommit,
			(holder, ex) -> holder.getRollback(),
			RxStatementRunnerHolder::getCommit);
	}
 
Example 3
Source File: PulsarRecordsStorage.java    From liiklus with MIT License 4 votes vote down vote up
@Override
public Publisher<Record> getPublisher() {
    return Flux.usingWhen(
            Mono.fromCompletionStage(() -> {
                var consumerBuilder = pulsarClient.newConsumer()
                        .acknowledgmentGroupTime(0, TimeUnit.SECONDS) // we don't ack here at all
                        .subscriptionName(groupName)
                        .subscriptionType(SubscriptionType.Failover)
                        .topic(TopicName.get(topic).getPartition(partition).toString());

                autoOffsetReset
                        .map(it -> {
                            switch (it) {
                                case "earliest":
                                    return SubscriptionInitialPosition.Earliest;
                                case "latest":
                                    return SubscriptionInitialPosition.Latest;
                                default:
                                    return null;
                            }
                        })
                        .ifPresent(consumerBuilder::subscriptionInitialPosition);

                return consumerBuilder.subscribeAsync();
            }),
            consumer -> {
                return Mono
                        .fromCompletionStage(consumer::receiveAsync)
                        .repeat()
                        .onErrorResume(AlreadyClosedException.class, __ -> Mono.empty())
                        .map(message -> {
                            var key = message.getKey();
                            return new Record(
                                    toEnvelope(topic, key, message),
                                    extractTime(message),
                                    partition,
                                    toOffset(message.getMessageId())
                            );
                        })
                        .delaySubscription(
                                initialOffset.flatMap(offset -> {
                                    return Mono.fromCompletionStage(consumer.seekAsync(fromOffset(offset)));
                                })
                        );
            },
            consumer -> Mono.fromCompletionStage(consumer.closeAsync())
    );
}
 
Example 4
Source File: Pool.java    From reactor-pool with Apache License 2.0 3 votes vote down vote up
/**
 * Acquire a {@code POOLABLE} object from the pool upon subscription and declaratively use it, automatically releasing
 * the object back to the pool once the derived usage pipeline terminates or is cancelled. This acquire-use-and-release
 * scope is represented by a user provided {@link Function}.
 * <p>
 * This is typically useful when the resource (and its usage patterns) directly involve reactive APIs that can be
 * composed within the {@link Function} scope.
 * <p>
 * The {@link Mono} provided to the {@link Function} emits the {@code POOLABLE} as it becomes available. Cancelling
 * the {@link org.reactivestreams.Subscription} before the {@code POOLABLE} has been emitted will either avoid object
 * acquisition entirely or will translate to a {@link PooledRef#release() release} of the {@code POOLABLE}.
 *
 * @param scopeFunction the {@link Function} to apply to the {@link Mono} delivering the POOLABLE to instantiate and
 *                      trigger a processing pipeline around it
 * @return a {@link Flux}, each subscription to which represents an individual act of acquiring a pooled object,
 * processing it as declared in {@code scopeFunction} and automatically releasing it
 * @see #acquire()
 */
default <V> Flux<V> withPoolable(Function<POOLABLE, Publisher<V>> scopeFunction) {
    return Flux.usingWhen(
            acquire(),
            slot -> { POOLABLE poolable = slot.poolable();
            if (poolable == null) return Mono.empty();
            return scopeFunction.apply(poolable);
            },
            PooledRef::release,
            (ref, error) -> ref.release(),
            PooledRef::release);
}
 
Example 5
Source File: SemaphoreGlobalRateLimiter.java    From Discord4J with GNU Lesser General Public License v3.0 3 votes vote down vote up
/**
 * Provides a scope to perform reactive operations under this limiter resources. Resources are acquired on
 * subscription and released when the given stage has completed or terminated with an error.
 *
 * @param stage a {@link Mono} that will manage this limiter resources
 * @param <T> the type of the stage supplier
 * @return a {@link Mono} where each subscription represents acquiring a rate limiter resource
 */
public <T> Flux<T> withLimiter(Publisher<T> stage) {
    return Flux.usingWhen(
            acquire(),
            resource -> stage,
            this::release);
}