Controll StreamSubscription with RiverPod

Viewed 518

I was trying to create a streamBuilder with RiverPod. Main thing is i like to control the stream, like implementing pause, resume, cancel..., so that i can control the stream anywhere from app.

Model Class here

class Counter {
  int i = 0;
  late StreamSubscription subscription;
  StreamController<int> controller = StreamController<int>();
 
  Counter() {
    subscription = _setUp().listen((event) {
      print(event);
    });
  }
 
  resume() {
    subscription.resume();
  }
 
  Stream<int> _setUp() {
    Timer.periodic(Duration(seconds: 1), (timer) {
      controller.add(i++);
    });
 
    return controller.stream;
  }
}

Then I've created a Stream for RiverPod

final myStream = StreamProvider.autoDispose<Counter>((ref) async* {
  final counter = Counter();
 
  ref.onDispose(() => counter.controller.sink.close());
 
  await for (final value in counter.controller.stream) {
    if (value == 10) counter.controller.sink.close();
 
    yield counter;
  }
});

And Widget here

 Column(
        children: [
          Consumer(
            builder: (context, watch, child) {
              final counter = watch(myStream);
 
              return counter.when(
                data: (data) {
                  return Text("data: ${data.toString()}");
                },
                loading: () => const CircularProgressIndicator(),
                error: (error, stackTrace) => Text("Err ${error.toString()}"),
              );
            },
            child: Text("Controll"),
          ),

          ///pause
          RaisedButton(
            onPressed: pause,
            child: Text("Pause"),
          ),
        ],
      ),
0 Answers
Related