Advertisement
Guest User

Untitled

a guest
Mar 24th, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. // similar to Flux::groupBy but closes the GroupedFlux whenever a different key value appears potentially opening another one for the same value later.
  2.  
  3.  
  4. @Test
  5. public void groupOnSwitch() {
  6. StepVerifier
  7. .create(
  8. groupOnSwitch(
  9. Flux.just("one", "two", "twenty", "tissue", "berta", "blot", "thousand"),
  10. s -> s.substring(0, 1))
  11. .flatMap(Flux::materialize)
  12. .map(s -> s.isOnComplete() ? "WINDOW CLOSED" : s.get())
  13. )
  14. .expectNext("one", "WINDOW CLOSED")
  15. .expectNext("two", "twenty", "tissue", "WINDOW CLOSED")
  16. .expectNext("berta", "blot", "WINDOW CLOSED")
  17. .expectNext("thousand", "WINDOW CLOSED")
  18. .verifyComplete();
  19. }
  20.  
  21. @Test
  22. public void groupOnSwitchKeys() {
  23.  
  24. Flux<GroupedFlux<String, String>> fluxOfGroupedFluxes = groupOnSwitch(
  25. Flux.just("one", "two", "twenty", "tissue", "berta", "blot", "thousand"),
  26. s -> s.substring(0, 1));
  27. StepVerifier.create(
  28. fluxOfGroupedFluxes.map(gf -> gf.key())
  29. )
  30. .expectNext("o", "t", "b", "t")
  31. .verifyComplete();
  32. }
  33.  
  34. private static <T, X> Flux<GroupedFlux<X, T>> groupOnSwitch(Flux<T> flux, Function<T, X> keyFunction) {
  35. ChangeTrigger changeTrigger = new ChangeTrigger();
  36. Flux<GroupedFlux<T, T>> fluxOfGroupedFluxes = flux.windowUntil(l -> changeTrigger.test(keyFunction.apply(l)), true);
  37. return fluxOfGroupedFluxes.flatMap(gf -> gf.groupBy(t -> keyFunction.apply(gf.key())));
  38. }
  39.  
  40. private static class ChangeTrigger<T> {
  41.  
  42. T last = null;
  43.  
  44. boolean test(T value) {
  45. boolean startNew = !Objects.equals(last, value);
  46. last = value;
  47. System.out.println(String.format("%s, %s", value, startNew));
  48. return startNew;
  49. }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement