Skip to content

StreamSubscription<T> abstract interface

abstract interface class StreamSubscription<T>

A subscription on events from a Stream.

When you listen on a Stream using Stream.listen, a StreamSubscription object is returned.

The subscription provides events to the listener, and holds the callbacks used to handle the events. The subscription can also be used to unsubscribe from the events, or to temporarily pause the events from the stream.

Example:

dart
final stream = Stream.periodic(const Duration(seconds: 1), (i) => i * i)
    .take(10);

final subscription = stream.listen(print); // A StreamSubscription<int>.

To pause the subscription, use pause.

dart
// Do some work.
subscription.pause();
print(subscription.isPaused); // true

To resume after the pause, use resume.

dart
// Do some work.
subscription.resume();
print(subscription.isPaused); // false

To cancel the subscription, use cancel.

dart
// Do some work.
subscription.cancel();

Properties

hashCode no setter inherited

int get hashCode

The hash code for this object.

A hash code is a single integer which represents the state of the object that affects operator == comparisons.

All objects have hash codes. The default hash code implemented by Object represents only the identity of the object, the same way as the default operator == implementation only considers objects equal if they are identical (see identityHashCode).

If operator == is overridden to use the object state instead, the hash code must also be changed to represent that state, otherwise the object cannot be used in hash based data structures like the default Set and Map implementations.

Hash codes must be the same for objects that are equal to each other according to operator ==. The hash code of an object should only change if the object changes in a way that affects equality. There are no further requirements for the hash codes. They need not be consistent between executions of the same program and there are no distribution guarantees.

Objects that are not equal are allowed to have the same hash code. It is even technically allowed that all instances have the same hash code, but if clashes happen too often, it may reduce the efficiency of hash-based data structures like HashSet or HashMap.

If a subclass overrides hashCode, it should override the operator == operator as well to maintain consistency.

Inherited from Object.

Implementation
dart
external int get hashCode;

isPaused no setter

bool get isPaused

Whether the StreamSubscription is currently paused.

If there have been more calls to pause than to resume on this stream subscription, the subscription is paused, and this getter returns true.

Returns false if the stream can currently emit events, or if the subscription has completed or been cancelled.

Implementation
dart
bool get isPaused;

runtimeType no setter inherited

Type get runtimeType

A representation of the runtime type of the object.

Inherited from Object.

Implementation
dart
external Type get runtimeType;

Methods

asFuture()

Future<E> asFuture<E>([E? futureValue])

Returns a future that handles the onDone and onError callbacks.

This method overwrites the existing onDone and onError callbacks with new ones that complete the returned future.

In case of an error the subscription will automatically cancel (even when it was listening with cancelOnError set to false).

In case of a done event the future completes with the given futureValue.

If futureValue is omitted, the value null as E is used as a default. If E is not nullable, this will throw immediately when asFuture is called.

Implementation
dart
Future<E> asFuture<E>([E? futureValue]);

cancel()

Future<void> cancel()

Cancels this subscription.

After this call, the subscription no longer receives events.

The stream may need to shut down the source of events and clean up after the subscription is canceled.

Returns a future that is completed once the stream has finished its cleanup.

Typically, cleanup happens when the stream needs to release resources. For example, a stream might need to close an open file (as an asynchronous operation). If the listener wants to delete the file after having canceled the subscription, it must wait for the cleanup future to complete.

If the cleanup throws, which it really shouldn't, the returned future completes with that error.

Implementation
dart
Future<void> cancel();

noSuchMethod() inherited

dynamic noSuchMethod(Invocation invocation)

Invoked when a nonexistent method or property is accessed.

A dynamic member invocation can attempt to call a member which doesn't exist on the receiving object. Example:

dart
dynamic object = 1;
object.add(42); // Statically allowed, run-time error

This invalid code will invoke the noSuchMethod method of the integer 1 with an Invocation representing the .add(42) call and arguments (which then throws).

Classes can override noSuchMethod to provide custom behavior for such invalid dynamic invocations.

A class with a non-default noSuchMethod invocation can also omit implementations for members of its interface. Example:

dart
class MockList<T> implements List<T> {
  noSuchMethod(Invocation invocation) {
    log(invocation);
    super.noSuchMethod(invocation); // Will throw.
  }
}
void main() {
  MockList().add(42);
}

This code has no compile-time warnings or errors even though the MockList class has no concrete implementation of any of the List interface methods. Calls to List methods are forwarded to noSuchMethod, so this code will log an invocation similar to Invocation.method(#add, [42]) and then throw.

If a value is returned from noSuchMethod, it becomes the result of the original invocation. If the value is not of a type that can be returned by the original invocation, a type error occurs at the invocation.

The default behavior is to throw a NoSuchMethodError.

Inherited from Object.

Implementation
dart
@pragma("vm:entry-point")
@pragma("wasm:entry-point")
external dynamic noSuchMethod(Invocation invocation);

onData()

void onData((void Function(T data))? handleData)

Replaces the data event handler of this subscription.

The handleData function is called for each data event of the stream after this function is called. If handleData is null, data events are ignored.

This method replaces the current handler set by the invocation of Stream.listen or by a previous call to onData.

Implementation
dart
void onData(void handleData(T data)?);

onDone()

void onDone((void Function())? handleDone)

Replaces the done event handler of this subscription.

The handleDone function is called when the stream closes. The value may be null, in which case no function is called.

This method replaces the current handler set by the invocation of Stream.listen, by calling asFuture, or by a previous call to onDone.

Implementation
dart
void onDone(void handleDone()?);

onError()

void onError(Function? handleError)

Replaces the error event handler of this subscription.

The handleError function must be able to be called with either one positional argument, or with two positional arguments where the seconds is always a StackTrace.

The handleError argument may be null, in which case further error events are considered unhandled, and will be reported to Zone.handleUncaughtError.

The provided function is called for all error events from the stream subscription.

This method replaces the current handler set by the invocation of Stream.listen, by calling asFuture, or by a previous call to onError.

Implementation
dart
void onError(Function? handleError);

pause()

void pause([Future<void>? resumeSignal])

Requests that the stream pauses events until further notice.

While paused, the subscription will not fire any events. If it receives events from its source, they will be buffered until the subscription is resumed. For non-broadcast streams, the underlying source is usually informed about the pause, so it can stop generating events until the subscription is resumed.

To avoid buffering events on a broadcast stream, it is better to cancel this subscription, and start to listen again when events are needed, if the intermediate events are not important.

If resumeSignal is provided, the stream subscription will undo the pause when the future completes, as if by a call to resume. If the future completes with an error, the stream will still resume, but the error will be considered unhandled and is passed to Zone.handleUncaughtError.

A call to resume will also undo a pause.

If the subscription is paused more than once, an equal number of resumes must be performed to resume the stream. Calls to resume and the completion of a resumeSignal are interchangeable - the pause which was passed a resumeSignal may be ended by a call to resume, and completing the resumeSignal may end a different pause.

It is safe to resume or complete a resumeSignal even when the subscription is not paused, and the resume will have no effect.

Implementation
dart
void pause([Future<void>? resumeSignal]);

resume()

void resume()

Resumes after a pause.

This undoes one previous call to pause. When all previously calls to pause have been matched by a calls to resume, possibly through a resumeSignal passed to pause, the stream subscription may emit events again.

It is safe to resume even when the subscription is not paused, and the resume will have no effect.

Implementation
dart
void resume();

toString() inherited

String toString()

A string representation of this object.

Some classes have a default textual representation, often paired with a static parse function (like int.parse). These classes will provide the textual representation as their string representation.

Other classes have no meaningful textual representation that a program will care about. Such classes will typically override toString to provide useful information when inspecting the object, mainly for debugging or logging.

Inherited from Object.

Implementation
dart
external String toString();

Operators

operator ==() inherited

bool operator ==(Object other)

The equality operator.

The default behavior for all Objects is to return true if and only if this object and other are the same object.

Override this method to specify a different equality relation on a class. The overriding method must still be an equivalence relation. That is, it must be:

  • Total: It must return a boolean for all arguments. It should never throw.

  • Reflexive: For all objects o, o == o must be true.

  • Symmetric: For all objects o1 and o2, o1 == o2 and o2 == o1 must either both be true, or both be false.

  • Transitive: For all objects o1, o2, and o3, if o1 == o2 and o2 == o3 are true, then o1 == o3 must be true.

The method should also be consistent over time, so whether two objects are equal should only change if at least one of the objects was modified.

If a subclass overrides the equality operator, it should override the hashCode method as well to maintain consistency.

Inherited from Object.

Implementation
dart
external bool operator ==(Object other);