Several things to take in account
Missleading names
Then I'd make a function called
User.update()
that just pulls userdata from the server and populates the User class properties. This is the only function that would be allowed to write over the User properties.
Whoever is familiar with the Active Record design pattern would be fooled by the method's name.
While we might expect to be pushing the changes to the server , the reality -according with the question- would be right the opposite!!!
If we are pulling the latest User
representation, then we should consider changing the method name to something like retrieve , refresh or reload. If we are really synchronizing, sync would be more self-descriptive than update.
Too many pulls
I would run the
User.update()
function during times such as:
- App launch
- App re-opened from sleep
- Profile update
- After in-app-purchase
- etc.
If we need to retrive the User
state so often, it probably means that we should not hold its state in the locale storage. Or -at least- not completely.1
Ideally, we do pull only when has been proven that the User
state has been modifed and we need its current state. Otherwise any event on the client-side is as good as any other. Such randomness eventually lead us to retrieve half DB with no consistent reasons.
If App re-opened from sleep
is a good moment for a User
refresh, why should not be good for any other entity?
Keep also in mind that connections consume a lot of resources and it also as an impact on the user's data plan. So I would constrain HTTP calls to the essential.
Consider holding the proper URIs and retrieve them as soon as you need'em, but don't hold the representantations if you find yourself synchronizing them often.
For instance, we can retrieve and hold data that is unlikely to change
GET /user/1
HTTP 200 OK
{
"fullname":"Cheewacka"
}
And keep the identifiers of those resources sensible to be retrieved often. For instance, /user/1/profile
or /user/1/score
.
Retrieve these resources only when the business need them and not randomly after random events of the application. Be consistent.
Finally, consider who else is going to be changing the User
beside the user itself. If there's no concurrency, probably the client application always has the most up-to-date representation. Or part of it.
1: Keep in mind that, what we do with the local storage is caching. If we have to expire the cache often, it probably means that we don't need cache at all. Or that we are caching the wrong data.