Refreshing our service

We are almost done describing our TaskService, but there is one more aspect we need to cover. Our service doesn't take into account that a third party might make changes to the endpoint database. We will see those changes if we move away from the component or reload the entire application. If we want to see those changes when they happen, we need to have some kind of behavior that tells us when data has changed. It is tempting to think of a polling solution and just refresh the data at certain intervals. This might be a painful approach, though, as the data we fetch might consist of a large object graph. Ideally, we only want to fetch what really changed and amend that to our application. Why do we care so much about this in the age of broadband connections? Here is the problem—an application should be able to be used on a mobile app and both speed as well as mobile data contracts might be an issue, so we need to consider the mobile user. Here are some things we should consider:

  • The size of the data
  • The polling interval 

If the expected size of the data is really big, then it might be a good idea to poke an endpoint and ask it for everything that changed after a certain time; this would change the size of the payload drastically. We could also just ask for a partial object graph back. The polling interval is another thing to consider. We need to ask ourselves: how often do we really need to refetch all the data? The answer could be never. 

Let's say we opt for an approach where we ask for the delta (the change after a certain time); it could look like the following:

constructor(){
lastFetchedDate;
INTERVAL_IN_SECONDS = 30;

setInterval(() => {
fetchTasksDelta( lastFetchedDate );
lastFetchedDate = DateTime.now;
}, this.INTERVAL_IN_SECONDS * 1000)
}

Regardless of what approach and considerations you take here, remember that not all users are on a broadband connection. It's also worth nothing that more and more of theses refresh scenarios tend to be solved with Web Sockets nowadays so you create an open connection between server and client, and the server can decide when it's time to send the client some new data. We will leave it to you, dear reader, to refactor this example using Sockets.

We now have a service which is:

  • Stateless
  • Able to handle offline connections
  • Able to cater for other data services such as sockets
  • Able to refresh its data at a certain interval

All this was made possible through the BehaviourSubject and localStorage. Don't just treat RxJS as an add-on to a Promise, but use its constructs and operators to craft robust services and architecture patterns.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset