NiRR
NiRR

Reputation: 5022

pusher api: how can I check if the connection is established?

I'm using the pusher interface, and I would like to write a fallback for environments where the pusher service is unavailable. I can't find a way to check if the pusher subscription is ok.

I tried this

$scope.channel.bind('pusher:error', function() {
        console.log("pusher:error");
    });

and also pusher:subscription_error but it does nothing.

any help will be appreciated.

Upvotes: 1

Views: 10177

Answers (1)

leggetter
leggetter

Reputation: 15467

It's important to highlight the difference between connection and subscription.

  • A connection is a persistent connection to Pusher over which all communication takes place.
  • A subscription is a request for data. In Pusher these are represented by channels. Subscriptions and associated data use the established connection and multiple subscriptions are multiplexed over a single connection.

To determine if the Pusher service is reachable or not you should check the connection state.

However, if you ever see this I'd also recommend contacting Pusher support since this shouldn't happen.

Detecting & Querying Connection State

It's possible to detect connection state by binding to events on the connection object.

pusher.connection.bind('state_change', function(states) {
  var prevState = states.previous;
  var currState = states.current;
});

You can additional get the state right now.

var currentState = pusher.connection.state;

Full documentation on this can be found here: https://pusher.com/docs/client_api_guide/client_connect#connection-states

The example in the questions appears to use Angular so you'll need to get reference to the connection object from the $scope. If you're using pusher-angular then the API should be the same as the normal Pusher library.

Subscription Status

You can bind to two events to determine the result of a subscription:

  • pusher:subscription_succeeded
  • pusher:subscription_error

The code to use these looks as follows:

var channel = pusher.subscribe('my-channel');

channel.bind('pusher:subscription_succeeded', function() {
  // Yipee!!
});

channel.bind('pusher:subscription_error', function() {
  // Oh nooooos!
});

Documentation on the success event can be found here: https://pusher.com/docs/client_api_guide/client_events#subscription_succeeded

Docs on the error event can be found here: https://pusher.com/docs/client_api_guide/client_events#subscription_error

Upvotes: 14

Related Questions