Created
November 15, 2018 08:11
-
-
Save imaximix/4723ee43d21886fccff5015d23629ec9 to your computer and use it in GitHub Desktop.
Server Sent Events with WebFlux
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from "react"; | |
export default class EventViewer extends Component { | |
constructor() { | |
super(); | |
this.state = { events: [] }; | |
} | |
componentDidMount() { | |
var source = new EventSource("http://localhost:8080/stream-events"); | |
source.onmessage = ({ data }) => { | |
this.setState({ | |
events: [data, ...this.state.events] | |
}); | |
}; | |
} | |
renderEvents() { | |
const { events } = this.state; | |
return events.map(event => <div key={event}>{event}</div>); | |
} | |
render() { | |
return <div>{this.renderEvents()}</div>; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.time.OffsetDateTime; | |
import org.springframework.http.MediaType; | |
import org.springframework.web.bind.annotation.CrossOrigin; | |
import org.springframework.web.bind.annotation.GetMapping; | |
import org.springframework.web.bind.annotation.PostMapping; | |
import org.springframework.web.bind.annotation.RestController; | |
import reactor.core.Disposable; | |
import reactor.core.publisher.DirectProcessor; | |
import reactor.core.publisher.Flux; | |
@CrossOrigin | |
@RestController | |
public class SSEController { | |
// Singleton | |
DirectProcessor<String> hotSource = DirectProcessor.create(); | |
@PostMapping(path = "/stream-events") | |
public void addEvent() { | |
hotSource.onNext(OffsetDateTime.now().toString()); | |
} | |
@GetMapping(path = "/stream-events", produces = MediaType.TEXT_EVENT_STREAM_VALUE) | |
public Flux<String> streamEvents() { | |
return Flux.<String>create(emitter -> { | |
Disposable disposable = hotSource.subscribe(event -> emitter.next(event)); | |
emitter.onCancel(disposable); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment