Rails ActionCable asynchronous issue

34 views Asked by At

In my camera page, I need to manage the current users' session, thus I need to create a new session when a user enter the page and remove their session when they leave the page. And I need to display all the existing session to users. To detect the users leave the page, I'm using ActionCable, when the unsubscribe method is triggered, I will remove the session using the session id.

Everything works fine except when users refresh the page.

# Camera Controller
def show
    @new_session = Session.create!(time: Time.Zone.now)
    puts "Getting all sessions"
    @all_sessions = Session.all
end
# Camera Channel
def unsubscribed
    puts "Removing session"
    Session.where(id: params[:sid]).destroy_all
end

Below is what I expect to happen when users refresh the page

  1. User leave the page (unsubscribe is called, old session is removed)
  2. User enter the page again (show is called, only newly created session is included in the "@new_session"

However, I found that "Removing session" is always printed after "Getting all sessions", which means the unsubscribed method is executed after show, thus I will always get the old session that supposed to be deleted.

I can't find any related post, any help would be appreciated.

0

There are 0 answers