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 {
31-
32- eventFlux = Flux .generate (e -> {
33- Event event = new Event (UUID .randomUUID ()
34- .toString (),
35- LocalDateTime .now ()
36- .toString ());
37- e .next (event );
38- });
27+ private Flux <Event > intervalFlux = Flux .interval (Duration .ofMillis (1000L )).zipWith (eventFlux , (time , event ) -> event );
3928
40- intervalFlux = Flux .interval (Duration .ofMillis (1000L ))
41- .zipWith (eventFlux , (time , event ) -> event );
42-
43- }
29+ private ObjectMapper json = new ObjectMapper ();
4430
4531 /**
4632 * On each new client session, send the message flux to the client.
@@ -50,7 +36,7 @@ private void init() throws InterruptedException {
5036 */
5137 @ Override
5238 public Mono <Void > handle (WebSocketSession webSocketSession ) {
53- ObjectMapper json = new ObjectMapper ();
39+
5440 return webSocketSession .send (intervalFlux .map (event -> {
5541 try {
5642 String jsonEvent = json .writeValueAsString (event );
@@ -60,12 +46,9 @@ public Mono<Void> handle(WebSocketSession webSocketSession) {
6046 e .printStackTrace ();
6147 return "" ;
6248 }
63- })
64- .map (webSocketSession ::textMessage ))
49+ }).map (webSocketSession ::textMessage ))
6550
66- .and (webSocketSession .receive ()
67- .map (WebSocketMessage ::getPayloadAsText )
68- .log ());
51+ .and (webSocketSession .receive ().map (WebSocketMessage ::getPayloadAsText ).log ());
6952 }
7053
7154}
0 commit comments