Daniel Taylor
Daniel Taylor

Reputation: 21

Detect unsubscribe from Action Cable on page change

I'm building a chat room type system in Rails and I need to detect when the user leaves the channel (i.e. closes the page) on the server so I can update the list of active users. I've searched the documentation and examples on GitHub and can't seem to find the answer.

I've used SignalR in the past, which triggers a disconnect event, but I can't find the equivalent (if it indeed exists) in Rails 5.

I can see examples with a unsubscribed method in the channel class, but this is never triggered whether I navigate to a new page or close the browser completely.

EDIT: Not sure if this helps but I'm not using turbolinks.

Upvotes: 1

Views: 2457

Answers (2)

bright
bright

Reputation: 191

Try this

App.chatroom.disconnected()
=> yourChannel stopped streaming from chatroom #rails terminal

App.chatroom = App.cable.subscriptions.create({channel: 
     'yourChannel'}, {

     disconnected: function () {
       App.cable.subscriptions.remove(this)
       this.perform('unsubscribed') #in the channel have a method 'unsubscibed' to update users
     },
 )}

Upvotes: 0

Daniel Taylor
Daniel Taylor

Reputation: 21

It was an issue with beta 2 of Rails 5. I've tried it in the latest version - beta 4 and it is now triggered as expected.

Here's the github issue for reference: https://github.com/rails/rails/pull/23715

Upvotes: 1

Related Questions