- Kotlin Blueprints
- Ashish Belagali Hardik Trivedi Akshay Chordiya
- 131字
- 2021-07-02 21:50:18
Event broadcaster
The ReactiveBroadcaster class is an event broadcaster that handles the responsibility of subscribing the observers and sending the updates to interested observers asynchronously and will also do the cleanup after the completion of the events:
/**
* Handles the event broadcasting to the observers in an
* asynchronous way.
*/
class ReactiveBroadcaster {
/**
* Set of emitters for multiple events
*/
private var emitters = synchronizedSet(HashSet<SseEmitter>())
/**
* Subscribe to the event
*/
fun subscribe(): SseEmitter {
val sseEmitter = SseEmitter()
// Stop observing the event on completion
sseEmitter.onCompletion(
{this.emitters.remove(sseEmitter)
})
this.emitters.add(sseEmitter)
return sseEmitter
}
/**
* Trigger the event update to the observers
*/
fun send(o: Any) {
synchronized(emitters) {
emitters.iterator().forEach {
try {
it.send(o, MediaType.APPLICATION_JSON)
} catch (e: IOException) {}
}
}
}
}