stacked icon indicating copy to clipboard operation
stacked copied to clipboard

unable to cancel a stream subscription using onDispose()

Open pieterbergmans opened this issue 2 years ago • 1 comments

Describe the bug

Hi. I'm following Dane's tutorial from 2019 on building a Location Service. I'm using the service in a single page of my app and I'm calling the service with StreamViewModel(). It works great but I want to turn off the subscription when the user navigates away from the page. I've tried calling onDispose in the ViewModelBuilder in my view but it doesn't get called.

class LocationView extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<LocationViewModel>.reactive(
      viewModelBuilder: () => LocationViewModel(),
      onDispose: (viewModel) async {
        await viewModel.cancelSubscription();
      },
      builder: (context, viewModel, child) => Scaffold(...));
  }

I've also tried adding an onDispose() method to the view class but that doesn't work either...

  @override
  void onDispose(LocationViewModel viewModel) {
    await viewModel.cancelSubscription();
  }

I have two questions:

  1. How can I call onDispose()?
  2. What method do I call for canceling a subscription? I'm currently calling the following from my ViewModel...
cancelSubscription() async {
    await streamSubscription!.cancel();
  }

To reproduce

None

Expected behavior

No response

Screenshots

No response

Additional Context

No response

pieterbergmans avatar Sep 12 '23 18:09 pieterbergmans

Hi @pieterbergmans I'm so happy to see more users using Stacked.

The stream is cancelled automatically when the view is disposed. You can see there here

Could you share the behaviour you're seeing that's showing you that the subscription is not cancelled. Logs or anything like that.

FilledStacks avatar Sep 29 '23 05:09 FilledStacks