Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disconnect and unsubscribe Action Cable on Rails 6

This was already asked here, but it seems that the old methods (example and example) no longer work on Rails 6 because you cannot use App.channel inside your app/javascript/channels/your_channel.js. Though, correct me if I'm wrong because I'm new to Rails.

My question is: how to disconnect or/and unsubscribe from client side on Rails 6?

I'm especially interested in the "on page change" scenario.

like image 832
Rafael Castro Avatar asked Oct 28 '25 05:10

Rafael Castro


2 Answers

The solution was to save the subscription on a this variable and do the remove call if this variable is not null when page loads, then do the new subscription.

// File: app/javascript/channels/your_channel.js
import consumer from "./consumer";

$(document).on('turbolinks:load', function() {
    if (this.subscription) {
        consumer.subscriptions.remove(this.subscription);
        console.log("unsubing");
    }

    if ($('#hashtag').attr('data-hashtag-id')) {
        var subscription = consumer.subscriptions.create({channel: "TweetsChannel", id: $('#hashtag').attr('data-hashtag-id')}, {
            connected() {
                console.log("we are live on: " + $('#hashtag').attr('data-hashtag-id'));
            },

            disconnected() {
                console.log("disconecting")
            },

            received(data) {
                $('#tweets-card').prepend(data.content)
            }
        });

        this.subscription = subscription;
    }
});
like image 80
Rafael Castro Avatar answered Oct 30 '25 23:10

Rafael Castro


Based on what you shared with us, I imagine you are trying to remove a subscription. You can remove it using consumer.subscriptions.remove [1].

Could you share the snippet of code you have in your app/javascript/channels/your_channel.js?

like image 32
alfakini Avatar answered Oct 30 '25 23:10

alfakini