StreamSubscription not cancel properly

Viewed 44

I am following this guide to build my App. Then, I add a document listener to the "users" collection. Now the problem is even if I log out of the first account and log in to the second account, the stream is still reading the previous document if I manually change the document using the console.

Account _userInfo = Account(email: '', name: '', typeName: '', fcmToken: '', isDisable: false);
Account get userInfo => _userInfo;

StreamSubscription<DocumentSnapshot>? userListener;

Future<void> init() async {
await Firebase.initializeApp(
  options: DefaultFirebaseOptions.currentPlatform,
);

FirebaseAuth.instance.userChanges().listen((user) async {
  if (user != null) {
    print('User != null');
    _loginState = ApplicationLoginState.loggedIn;
    await setFcmToken();
    listenToMyself();
  } else {
    print('User null');
    userListener?.cancel();
    _loginState = ApplicationLoginState.loggedOut;
  }
  notifyListeners();
});



void listenToMyself() {
    print('Listening to: ${FirebaseAuth.instance.currentUser!.uid}');
    userListener = usersCollection.doc(FirebaseAuth.instance.currentUser!.uid).snapshots().listen(
      (event) {
        print("current data: ${FirebaseAuth.instance.currentUser!.uid} ${event.data()}");
        _userInfo = Account.fromJson(event.data() as Map<String, dynamic>);
        notifyListeners();
      },
      onError: (error) => print("Listen failed: $error"),
    );
  }

  Future<void> setFcmToken() async {
    String? token = await FirebaseMessaging.instance.getToken();
    _token = token;
    await FirebaseFirestore.instance.collection('users').doc(FirebaseAuth.instance.currentUser!.uid).set({'fcmToken': token}, SetOptions(merge: true));
  }
0 Answers
Related