Reputation: 3451
I want to stop and restart a stream conditionally, how can I do that?
_fireStore
.collection(...)
.doc(...)
.snapshots().takeWhile((element) => _listenable);
Stream stops when _listenable
is false but doesn't restart when true ?
Anyone know how to do it?
Upvotes: 0
Views: 1274
Reputation: 589
You can use async to easily control the stream This is how you can do it.
First create a StreamSubsctiprion like this
StreamSubscription<QuerySnapshot>? _eventStream;
and then set a listener for your snapshots stream.
here is how you can store stream query snapshot
Stream<QuerySnapshot> streamSub =_fireStore
.collection(...)
.doc(...)
.snapshots();
add listener for your stream like this
_eventStream = streamSub.listen((snapshot) => _eventStream);
Then you can use your event stream to cancel, pause and resume your stream like this
_eventStream!.pause();
_eventStream!.cancel();
_eventStream!.resume();
here is my final code
class MainScreen extends State<PaymentScreen> {
StreamSubscription<QuerySnapshot>? _eventStream;
@override
Widget build(BuildContext context) {
Stream<QuerySnapshot> myStream = FirebaseFirestore.instance.collection('Users').snapshots();
return Scaffold(
body: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
StreamBuilder<QuerySnapshot>(
stream: myStream,
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return Text('Something went wrong');
}
if (snapshot.connectionState == ConnectionState.waiting) {
return Text("Loading");
}
return Column(
children:
snapshot.data!.docs.map((DocumentSnapshot document) {
Map<String, dynamic> data =
document.data()! as Map<String, dynamic>;
return ListTile(
title: Text(data['firstName']),
);
}).toList(),
);
},
),
FloatingActionButton.extended(
onPressed: () {
_eventStream = myStream.listen((snapshot) => _eventStream);
try {
_eventStream!.pause();
print('paused');
} catch (e, s) {
print(s);
}
},
label: const Text("Pause Stream"),
),
],
),
),
);
}
}
Upvotes: 3