Sagar Acharya
Sagar Acharya

Reputation: 3767

Better Approach to hit the api after the interval flutter

Currently working on home automation app, in which there is the events API that gives me the events if they are triggered. But i want to continuously run the API so that it will track the events that are triggered in the overall application. And there is a home page where i show the events in which ever occured. Its a simple rest APInot web sockets used, Its kind of request response type. Any suggestions that how can i implement it in a proper way. Currently using the Timer in every page.But this is not a good approach.

Upvotes: 0

Views: 1534

Answers (1)

Sanjay Sharma
Sanjay Sharma

Reputation: 4035

You would definitely need to use Timer.periodic() for period calls. I would suggest you follow this approach.

  1. Try to reduce it to only one API call by sending the required data in the same API so you can reduce the network load.
  2. Create a common service for fetching the event details by creating parent BLOC or provider as per your state management implementation.
  3. Run the periodic job every 10 sec or depending on your requirement.
  4. Don't call the API until the previous API response is fetched. You need to keep a track of it.
  5. The response can be reflected on UI after a successful response on all the pages by using the common consumer of the BLOC or Provider so the code will be modularized and you will be avoiding the duplicate code.
  6. Don't forget to dispose of the timer object.

Upvotes: 1

Related Questions