Marc Ma
Marc Ma

Reputation: 338

Check if StreamSubscription is canceled

To put it simple:

How do i check if a StreamSubscription is canceled?

There is no

_myCustomSub.isCanceled

Upvotes: 9

Views: 4692

Answers (4)

Pip
Pip

Reputation: 274

I've run into a similar situation and my solution was to make my StreamSubscription nullable and set it to null after cancel().

await _newAlertsStreamSubscription?.cancel().then((_) {
     _newAlertsStreamSubscription = null;
});

Upvotes: 4

Aleksandar
Aleksandar

Reputation: 4144

Yeah, as others said, it's kinda lame that there is no way of checking if the stream subscription is canceled. I guess you don't have access to the StreamController, so here are my two options.

  1. Set the _myCustomSub to null as a sign of canceled subscription and act accordingly.

  2. Another way would be to have a bool value (isSubCanceled) somewhere together with the _myCustomSub variable, and use it instead of _myCustomSub.isCanceled.

Upvotes: 0

Pablo Barrera
Pablo Barrera

Reputation: 10963

I think this might be what you're looking for:

final streamController = StreamController();
streamController.onCancel = (){};

According to the documentation: Creating streams in Dart

Waiting for a subscription

To be notified of subscriptions, specify an onListen argument when you create the StreamController. The onListen callback is called when the stream gets its first subscriber. If you specify an onCancel callback, it’s called when the controller loses its last subscriber.

Final hints

The onListen, onPause, onResume, and onCancel callbacks defined by StreamController are called by the stream when the stream’s listener state changes

In addition, this might be helpful:

//Whether there is a subscriber on the [Stream]
streamController.hasListener

Upvotes: 0

wildeyes
wildeyes

Reputation: 7507

It seems you'd have to use one of two methods:

  1. onDone method - and retain in a seperate variable whether the stream was closed, or..
  2. cancel method - and await the future that signals that the StreamSubscription was canceled.

Don't know of any other way.

Upvotes: 3

Related Questions