Home > database >  How to paginate and listen to the data and cancel unnecessary listeners in flutter effectively?
How to paginate and listen to the data and cancel unnecessary listeners in flutter effectively?

Time:02-14

Imagine I am trying to get an infinite scrolling similar to that of Instagram by paginating the post and I will also be listening to the post detail changes for each post that have been queried.

I start off by querying the first 10 posts:

void getPosts(){
postStream =
      firestore.collection('posts')
          .limit(10)
          .orderBy('createdAt', descending: true)
          .snapshots().listen((documentSnapshot) {... code to convert to each doc from JSON..}
}

As the user scrolls down, I detect the scroll with the listener and query for more posts

void getMorePosts(){
paginatedPostStream =
      firestore.collection('posts')
          .limit(10)
          .orderBy('createdAt', descending: true)
          .startAfterDocument(lastPostDocSnapshot)
          .snapshots().listen((documentSnapshot) {... code to convert to each doc from JSON..}
}

When the user no longer needs these post, I'll cancel the stream in the following way:

postStream.cancel();
paginatedPostStream.cancel();

However, I realized that doing so only stopped listening to the earliest and latest paginated stream. For example, the user may have queried in the following way

10 | 10 | 10 | 10 | 10
^                   ^

but the canceling of stream only applies for the first and last 10 posts queried. How can I more effectively cancel the listener to prevent data leakage?

Any suggestion is welcomed. Thank you.

CodePudding user response:

As discussed in the comments, you will need to manage all streams instead of just the first and last one. If you want to limit the resources being consumed, you will need to close each stream as it becomes obsolete.

There is no single best practice here, but most implementation I know of, implement a virtual window of few (say 3-5) screens full of information. So if in your case you can display 10 documents on the screen at once, you'd keep listeners on 3-5 streams of 10 documents: the information that is currently displayed and 1 or 2 screenfull's up and down. Any stream outside of this virtual window can then be cancelled to reduce resource consumption.

  • Related