I am trying to implement the firebase streams and pagination with my GetX. With my implementation the following issue arrises. The initial batch of fetched posts are streamed correctly and updated in the real time. However, the second batch of posts are not updated in the real time. It seems that the stream is not binded to the second batch of the posts. Here's the code:
ScrollController scrollController = ScrollController();
CollectionReference get _posts => FirebaseFirestore.instance.collection(FirebaseConstants.postsCollection);
RxList<PostModel> viewPost = RxList<PostModel>([]);
@override
void onInit() {
super.onInit();
viewPost.bindStream(getPosts());
}
Stream<List<PostModel>> getPosts() {
Stream<QuerySnapshot> snapshotStream;
void handleScroll() {
if (scrollController.position.maxScrollExtent ==
scrollController.position.pixels) {
var lastPost = viewPost.isNotEmpty ? viewPost.last : null;
_posts
.orderBy('createdAt', descending: true)
.startAfter([lastPost!.createdAt])
.limit(2)
.snapshots()
.listen((event) {
List<PostModel> newPosts = [];
for (var doc in event.docs) {
newPosts
.add(PostModel.fromMap(doc.data() as Map<String, dynamic>));
}
viewPost.addAll(newPosts);
});
}
}
scrollController.addListener(handleScroll);
snapshotStream =
_posts.orderBy('createdAt', descending: true).limit(7).snapshots();
return snapshotStream.map((event) {
List<PostModel> posts = [];
for (var doc in event.docs) {
posts.add(PostModel.fromMap(doc.data() as Map<String, dynamic>));
}
return posts;
});
}
I tried several different implementations, and I always encounter the same issue. The posts are fetched and displayed in the correct order. However, real-time updates work only for the initial batch of posts and not for the rest of them.