Hacker News new | ask | show | jobs
by ntlve 3531 days ago
I've found that the best way to deal with this complexity is to ensure that any concurrent work is done in a fire-and-forget kind of style. Concurrent work is submitted to a IntentService (possible backed by a thread pool instead of a single worker thread to speed things up) and if it needs to talk back to the UI it does so via a local sql-db or similar construct. That way the UI can die and get restarted indepedently of the worker service and the worker service can update UI state without having to care about the UI existing or not.
1 comments

This looks like absolutely the best approach, but there's one thing I don't like about it: communication between IntentServices and the UI thread feels so... wasteful. The sanest way to do it, I think, is keep communication to a minimum, relying solely on the local DB as a source of information. But then every operation you do to fetch remote data immediately results in at least a couple of DB operations (store it, read it) and a ton of serialization. As far as I know, there's no simple way to pass an object from the service to the UI.
> As far as I know, there's no simple way to pass an object from the service to the UI.

They are in the same process, you can communicate between them through all the normal Java mechanisms. For example, your UI can just register & unregister a callback on the service directly in its start/stop methods (or in onVisibilityChanged if you'd rather do this in a View instead)

Oh, that's better then. In documentation they always point you towards using complicated mechanisms for communication, but I suppose that only applies to services running in different processes. Thank you for the clarification.