Search code examples
flutterdartstreamlifecycle

How streams behave when flutter app transitions between AppLifecycleStates?


When a flutter app transitions to inactive, detached or paused it may have active stream subscriptions. What happens to these subscriptions when the app moves between those states? Should I take care of cancelling/restarting subscriptions when transitioning into particular states?


Solution

  • It depends if you want to pause a Stream while your app is inactive or paused.

    Changing the ApplifeCycle state do not pause a stream subscription when changing state, and do only cancel subscription when you close your app, if you mention it in dispose() method.

    You can try this code to test the behavior :

    class MyHomePage extends StatefulWidget {
      MyHomePage({Key key}) : super(key: key);
    
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> with WidgetsBindingObserver {
      StreamSubscription sub;
    
      @override
      void didChangeAppLifecycleState(AppLifecycleState state) {
        super.didChangeAppLifecycleState(state);
        print(state);
        print('Paused: ${sub.isPaused}');
    
        // Here you can cancel or pause subscriptions if necessary
        if (state == AppLifecycleState.paused) {
          sub.pause();
        }
    
      }
    
      @override
      void initState() {
        WidgetsBinding.instance.addObserver(this);
        sub = Stream.periodic(const Duration(seconds: 1))
            .listen(print);
        super.initState();
      }
    
      @override
      void dispose() {
        WidgetsBinding.instance.removeObserver(this);
        sub.cancel();
        super.dispose();
      }
    
      @override
      Widget build(BuildContext context) {
        return const SizedBox();
      }
    }