简体   繁体   中英

Pushing a value to a StreamProvider?

I have a Stream object that is a listener of a signed in user from a database reference (Firestore). I'm using it in a StreamProvider so that my app can listen to signals for users signing in or out.

There's a specific event that (email verified) which by design does not cause the Stream to emit a new value. I've been able to solve this by basically checking every few seconds seconds whether email has been verified, and if not, reloading the user object. This works great in of itself, but I'd like to connect it to the StreamProvider I'm already using for managing user state.

If there is a way to 'push' the user object (with email verified: true) that is in local scope to my create account widget, to the global StreamProvider , as if it were an actual update event coming from the database reference, then the rest of my app could listen for the email verified signal. How could this be done?

I already know I could just expose a new ChangeNotifier the state of which encapsulates whether or not email is verified, but I really would like it to be part of the user provider, to avoid a situation where user.isEmailVerified is false because user is stale.

You can't push items to a Stream instance. You need to have an access to a StreamSink instance.

Common implementations of StreamSink are

  • StreamController when using plain dart
  • BehaviorSubject or PublishSubject when using rxDart.

StreamController example:

import 'dart:async';

void main() {
  final streamController = StreamController();

  streamController.stream.listen(
    (event) => print('Event: $event'),
  );

  streamController.add(123); // prints "Event: 123"
}

BehaviorSubject example:

import 'package:rxdart/rxdart.dart';

void main() {
  final subject = BehaviorSubject<int>();

  subject.listen((value) {
    print('value: $value');
  });

  subject.add(123); //prints "value: 123"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM