Cancel subscriptions on dispose

This commit is contained in:
Vishnu Mohandas 2020-05-05 18:26:24 +05:30
parent b6c7bdffd8
commit c25ee04658
3 changed files with 22 additions and 5 deletions

View file

@ -1,3 +1,4 @@
import 'dart:async';
import 'dart:collection';
import 'package:flutter/cupertino.dart';
@ -29,10 +30,11 @@ class _GalleryState extends State<Gallery> {
final List<List<Photo>> _collatedPhotos = List<List<Photo>>();
Set<Photo> _selectedPhotos = HashSet<Photo>();
List<Photo> _photos;
StreamSubscription<LocalPhotosUpdatedEvent> _subscription;
@override
void initState() {
Bus.instance.on<LocalPhotosUpdatedEvent>().listen((event) {
_subscription = Bus.instance.on<LocalPhotosUpdatedEvent>().listen((event) {
setState(() {});
});
super.initState();
@ -179,4 +181,9 @@ class _GalleryState extends State<Gallery> {
firstDate.month == secondDate.month &&
firstDate.day == secondDate.day;
}
void dispose() {
_subscription.cancel();
super.dispose();
}
}

View file

@ -1,3 +1,5 @@
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:photos/core/event_bus.dart';
@ -28,10 +30,11 @@ class GalleryAppBarWidget extends StatefulWidget
class _GalleryAppBarWidgetState extends State<GalleryAppBarWidget> {
bool _hasSyncErrors = false;
StreamSubscription<RemoteSyncEvent> _subscription;
@override
void initState() {
Bus.instance.on<RemoteSyncEvent>().listen((event) {
_subscription = Bus.instance.on<RemoteSyncEvent>().listen((event) {
setState(() {
_hasSyncErrors = !event.success;
});
@ -162,4 +165,9 @@ class _GalleryAppBarWidgetState extends State<GalleryAppBarWidget> {
),
);
}
void dispose() {
_subscription.cancel();
super.dispose();
}
}

View file

@ -1,3 +1,4 @@
import 'dart:async';
import 'dart:collection';
import 'package:flutter/cupertino.dart';
@ -28,13 +29,14 @@ class _HomeWidgetState extends State<HomeWidget> {
ShakeDetector _detector;
int _selectedNavBarItem = 0;
Set<Photo> _selectedPhotos = HashSet<Photo>();
StreamSubscription<LocalPhotosUpdatedEvent> _subscription;
@override
void initState() {
Bus.instance.on<LocalPhotosUpdatedEvent>().listen((event) {
_subscription = Bus.instance.on<LocalPhotosUpdatedEvent>().listen((event) {
setState(() {});
});
_detector = ShakeDetector.waitForStart(
_detector = ShakeDetector.autoStart(
shakeThresholdGravity: 3,
onPhoneShake: () {
_logger.info("Emailing logs");
@ -45,7 +47,6 @@ class _HomeWidgetState extends State<HomeWidget> {
@override
Widget build(BuildContext context) {
_detector.startListening();
return Scaffold(
appBar: GalleryAppBarWidget(
widget.title,
@ -104,6 +105,7 @@ class _HomeWidgetState extends State<HomeWidget> {
@override
void dispose() {
_detector.stopListening();
_subscription.cancel();
super.dispose();
}
}