blackmouse572
blackmouse572

Reputation: 41

How to reduce/optimize api call when initial a bloc

I have a navbar, change between 2 screens nested with Provider create blocs. Whenever bloc constructor called. It's call api to get data and add to the stream. So the problem here, user can spam switch between 2 screens and make the bloc dispose and init => api was called multiple times.

Class Bloc1 {
  const Bloc1(){
    data = await fetch() //Call api
    stream1.add(data) //Then add to stream
 }
}

I have tried the lock. But it does not work because when recreate, the lock is recreate too -> useless.

Class Bloc1{
 var lock = false;
 const Bloc1(){
   if(lock == false) {
     data = await fetch() //Call api
     stream1.add(data) //Then add to stream
   }
 }
}

Upvotes: 0

Views: 455

Answers (1)

Fabián Bardecio
Fabián Bardecio

Reputation: 259

In my opinion, the issue you are mentioning is a kind of a border case where the user will have an aggressive behavior with the switch.

That being said, I think you should clarify a few points:

  • Do you really want to change the switch behavior to avoid this scenario?
  • Does it make sense to fetch new data every time the user switches tabs? I mean, does the data change that often? Because if the data does not change, maybe it does not makes sense to make a new request to the API at that point, and you should consider fetching this data at some other point.

I think there is no way to avoid this scenario if you instantiate/dispose your bloc every time the user switches screens (unless you save the lock or previously retrieved data outside the bloc, so next time you instantiate this bloc you can provide this value via the constructor, and this way you can avoid making the API request).

Depending on your Bloc logic, a solution could be that you instantiate the Bloc above these two screens, by doing this the Bloc will not be disposed once you switch screens and therefore it won't be instantiated again. Take into account that this approach will make the Bloc to be alive no matter how many times the user switches screens, and it is possible that this is something that you want to avoid.

Upvotes: 0

Related Questions