Skip to content

Instantly share code, notes, and snippets.

@timjonesdev
Created August 21, 2019 16:45
Show Gist options
  • Save timjonesdev/3f78327b991186d5a7f6537f7391c9d4 to your computer and use it in GitHub Desktop.
Save timjonesdev/3f78327b991186d5a7f6537f7391c9d4 to your computer and use it in GitHub Desktop.
The zip function, in action.
public Mono<ServerResponse> randomizeScore(ServerRequest request) {
String countString = request.pathVariable("count");
int count = Integer.parseInt(countString);
if (count < 0 || count > 40) {
return ServerResponse.badRequest().body(BodyInserters.fromObject("Count must be between 0 and 40"));
}
Flux<String> playerNames = this.teamRepository.findAll()
.map(Team::getPlayers)
.map(players -> players.stream().map(Player::getName))
// collect lists into a Flux of Strings
.flatMap(Flux::fromStream)
// convert to a Mono of List<String>
.collectList()
.map(list -> {
// work with the single unified list
while (list.size() < count) {
// Double the size of the list until it's bigger than the count
list.addAll(list);
}
// randomize by shuffling order
Collections.shuffle(list);
return list;
})
.flatMapMany(Flux::fromIterable);
Flux<Double> doubleFlux = Flux.interval(Duration.ofMillis(1000))
.map(pulse -> this.randomDouble())
.take(count);
// combine the two fluxes and update player scores with random Doubles
Flux<Team> updateFlux = Flux.zip(doubleFlux, playerNames)
.flatMap(objects -> {
Double scoreChange = objects.getT1();
String name = objects.getT2();
return this.updateTeam(name, scoreChange);
});
return ServerResponse.ok().body(BodyInserters.fromPublisher(updateFlux, Team.class));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment