@@ -151,6 +151,7 @@ function Subscription(streamId, callback, options) {
151151 this . bind ( 'unsubscribed' , function ( ) {
152152 debug ( "Sub %s unsubscribed: %s" , _this . id , _this . streamId )
153153 _this . subscribed = false
154+ _this . unsubscribing = false
154155 _this . resending = false
155156 } )
156157
@@ -303,12 +304,14 @@ StreamrClient.prototype._addSubscription = function(sub) {
303304StreamrClient . prototype . _removeSubscription = function ( sub ) {
304305 delete this . subById [ sub . id ]
305306
306- this . subsByStream [ sub . streamId ] = this . subsByStream [ sub . streamId ] . filter ( function ( it ) {
307- return it !== sub
308- } )
307+ if ( this . subsByStream [ sub . streamId ] ) {
308+ this . subsByStream [ sub . streamId ] = this . subsByStream [ sub . streamId ] . filter ( function ( it ) {
309+ return it !== sub
310+ } )
309311
310- if ( this . subsByStream [ sub . streamId ] . length === 0 )
311- delete this . subsByStream [ sub . streamId ]
312+ if ( this . subsByStream [ sub . streamId ] . length === 0 )
313+ delete this . subsByStream [ sub . streamId ]
314+ }
312315}
313316
314317StreamrClient . prototype . getSubscriptions = function ( streamId ) {
@@ -353,11 +356,12 @@ StreamrClient.prototype.unsubscribe = function(sub) {
353356 throw "unsubscribe: please give a Subscription object as an argument!"
354357
355358 // If this is the last subscription for this stream, unsubscribe the client too
356- if ( this . subsByStream [ sub . streamId ] . length === 1 && this . connected && ! this . disconnecting && sub . isSubscribed ( ) ) {
359+ if ( this . subsByStream [ sub . streamId ] . length === 1 && this . connected && ! this . disconnecting && sub . isSubscribed ( ) && ! sub . unsubscribing ) {
360+ sub . unsubscribing = true
357361 this . _requestUnsubscribe ( sub . streamId )
358362 }
359- // Else the sub can be cleaned off' immediately
360- else {
363+ // Else the sub can be cleaned off immediately
364+ else if ( ! sub . unsubscribing ) {
361365 this . _removeSubscription ( sub )
362366 sub . trigger ( 'unsubscribed' )
363367 this . _checkAutoDisconnect ( )
@@ -465,12 +469,14 @@ StreamrClient.prototype.connect = function(reconnect) {
465469 this . socket . on ( 'unsubscribed' , function ( response ) {
466470 debug ( "Client unsubscribed: %o" , response )
467471
468- // Copy the list to avoid concurrent modifications
469- var l = _this . subsByStream [ response . channel ] . slice ( )
470- l . forEach ( function ( sub ) {
471- _this . _removeSubscription ( sub )
472- sub . trigger ( 'unsubscribed' )
473- } )
472+ if ( _this . subsByStream [ response . channel ] ) {
473+ // Copy the list to avoid concurrent modifications
474+ var l = _this . subsByStream [ response . channel ] . slice ( )
475+ l . forEach ( function ( sub ) {
476+ _this . _removeSubscription ( sub )
477+ sub . trigger ( 'unsubscribed' )
478+ } )
479+ }
474480
475481 _this . _checkAutoDisconnect ( )
476482 } )
0 commit comments