Last active
March 20, 2024 18:58
-
-
Save salmanasiddiqui/cd8a452d6a81bc4b050b to your computer and use it in GitHub Desktop.
Right way to use Rails SSE for live notification
This file contains hidden or 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
class NotificationsController < ApplicationController | |
def notify_me | |
# Rails reserve a db connection from connection pool for each request, lets put it back into connection pool. | |
ActiveRecord::Base.clear_active_connections! | |
# required header | |
response.headers['Content-Type'] = 'text/event-stream' | |
sse = ActionController::Live::SSE.new(response.stream) | |
@notification = nil | |
# This @time will be used to send a heartbeat to client, so that if client has closed his window then we will know. | |
@time = Time.now | |
begin | |
loop do | |
@notification = # put your data to be streamed here | |
# send heartbeat every 1 minute | |
if @notification || @time + 1.minute < Time.now | |
sse.write(@notification.to_json) | |
@notification = nil | |
@time = Time.now | |
end | |
sleep 0.001 | |
end | |
rescue ActionController::Live::ClientDisconnected | |
# client disconnected | |
ensure | |
sse.close | |
end | |
render nothing: true | |
end | |
# Code that allows us to only mix in the live methods if we're accessing the desired action | |
def dispatch(name, *args) | |
extend ActionController::Live if name.to_s == 'notify_me' | |
super | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment