1212import reactor .core .publisher .Flux ;
1313import reactor .core .publisher .Mono ;
1414
15- import javax .annotation .PostConstruct ;
1615import java .time .Duration ;
1716import java .time .LocalDateTime ;
1817import java .util .UUID ;
1918
2019@ Component
2120public class ReactiveWebSocketHandler implements WebSocketHandler {
2221
23- private Flux <Event > eventFlux ;
24- private Flux <Event > intervalFlux ;
22+ private Flux <Event > eventFlux = Flux .generate (e -> {
23+ Event event = new Event (UUID .randomUUID ().toString (), LocalDateTime .now ().toString ());
24+ e .next (event );
25+ });
2526
26- /**
27- * Here we prepare a Flux that will emit a message every second
28- */
29- @ PostConstruct
30- private void init () throws InterruptedException {
27+ private Flux <Event > intervalFlux = Flux .interval (Duration .ofMillis (1000L )).zipWith (eventFlux , (time , event ) -> event );
3128
32- eventFlux = Flux .generate (e -> {
33- Event event = new Event (UUID .randomUUID ()
34- .toString (),
35- LocalDateTime .now ()
36- .toString ());
37- e .next (event );
38- });
29+ private ObjectMapper json = new ObjectMapper ();
3930
40- intervalFlux = Flux .interval (Duration .ofMillis (1000L ))
41- .zipWith (eventFlux , (time , event ) -> event );
42-
43- }
44-
45- /**
46- * On each new client session, send the message flux to the client.
47- * Spring subscribes to the flux and send every new flux event to the WebSocketSession object
48- * @param session
49- * @return Mono<Void>
50- */
5131 @ Override
5232 public Mono <Void > handle (WebSocketSession webSocketSession ) {
53- ObjectMapper json = new ObjectMapper ();
33+
5434 return webSocketSession .send (intervalFlux .map (event -> {
5535 try {
5636 String jsonEvent = json .writeValueAsString (event );
@@ -60,12 +40,9 @@ public Mono<Void> handle(WebSocketSession webSocketSession) {
6040 e .printStackTrace ();
6141 return "" ;
6242 }
63- })
64- .map (webSocketSession ::textMessage ))
43+ }).map (webSocketSession ::textMessage ))
6544
66- .and (webSocketSession .receive ()
67- .map (WebSocketMessage ::getPayloadAsText )
68- .log ());
45+ .and (webSocketSession .receive ().map (WebSocketMessage ::getPayloadAsText ).log ());
6946 }
7047
7148}
0 commit comments