Convert Consumer<Foo> to Function<Flux<Foo>,Mono<Void>>

This results in a better experience for users because the consumer
that they write is only applied to a Flux that is subscribed to
by the framework once. It gives better control over the flow of
foos, e.g. if some component wants to subscribe on a thread.
This commit is contained in:
Dave Syer
2018-03-26 10:06:13 +01:00
parent a1b624b28a
commit 5aeba1ea96
13 changed files with 144 additions and 76 deletions

View File

@@ -30,6 +30,7 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
/**
* @author Mark Fisher
@@ -45,9 +46,11 @@ public class TaskConfiguration {
@Bean
public CommandLineRunner commandLineRunner(FunctionCatalog registry) {
final Supplier<Flux<Object>> supplier = registry.lookup(Supplier.class, properties.getSupplier());
final Function<Flux<Object>, Flux<Object>> function = registry.lookup(Function.class, properties.getFunction());
final Consumer<Flux<Object>> consumer = registry.lookup(Consumer.class, properties.getConsumer());
final Supplier<Flux<Object>> supplier = registry.lookup(Supplier.class,
properties.getSupplier());
final Function<Flux<Object>, Flux<Object>> function = registry
.lookup(Function.class, properties.getFunction());
final Consumer<Flux<Object>> consumer = consumer(registry);
CommandLineRunner runner = new CommandLineRunner() {
@Override
@@ -57,4 +60,15 @@ public class TaskConfiguration {
};
return runner;
}
private Consumer<Flux<Object>> consumer(FunctionCatalog registry) {
Consumer<Flux<Object>> consumer = registry.lookup(Consumer.class,
properties.getConsumer());
if (consumer != null) {
return consumer;
}
Function<Flux<Object>, Mono<Void>> function = registry.lookup(Function.class,
properties.getConsumer());
return flux -> function.apply(flux).subscribe();
}
}