Stop listening and restart listening to a stream in RxDart

Issue

I have one class in my application that is adding values to a BehaviorSubject stream:

class MyClassA{

    BehaviorSubject<int> _signalSubject = BehaviorSubject();
    Stream<int> get signalStream => _signalSubject.stream;

    //at some other point in the same class i have:
    _signalSubject.add(someIntValue)

}

Now, on another class in my application I have:

  class MyClassWidget extends StatefulWidget {
      MyClassWidget();

      @override
      _MyClassWidgetState createState() => _MyClassWidgetState();
    }

    class _MyClassWidgetState extends State<MyClassWidget>{

        MyClassA classA = MyClassA();
        ... etc

        @override
        void initState() {
        super.initState();

        classA.signalStream
            .listen((signal) => print("Signal received $signal"));

    });
  }

 }

Is it possible to stop listening to signalStream under certain condition and re-start listening again under another condition?

The stream has the property .takeUntil which, as far as I understand, could be used to stop listening, but how to re-start listening again?

Solution

From https://api.flutter.dev/flutter/dart-async/StreamSubscription-class.html, you can see that you have pause and resume methods for StreamSubscription objects.


pause([Future resumeSignal]) → void

Request that the stream pauses events until further notice.

resume() → void

Resume after a pause.

Also from https://api.flutter.dev/flutter/dart-async/Stream-class.html:

” You listen on a stream to make it start generating events, and to set up listeners that receive the events. When you listen, you receive a StreamSubscription object which is the active object providing the events, and which can be used to stop listening again, or to temporarily pause events from the subscription.”

So when you start listening to the stream, It returns a StreamSubscription object. By using that, You can pause and resume it when you want.

Answered By – Morez

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.