Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern for multiple Loaders with LoaderManager?

I'm using Fragments and LoaderManager. I have to launch an unknown number of tasks, and they might be run in parallel (otherwise I'd just reuse one and only one loader). For example, I have a listview, and each row might have a button to save the content of that row to a webserver. The user could initiate a save request on multiple items in parallel.

private int nextId = 0;

private void onClickListener() {
    Bundle bundle = new Bundle();
    bundle.putNextData(...);
    getLoaderManager().initLoader(nextId++, bundle, this);
}

I could try bookkeeping myself, so create a pool of loaders manually and reuse them when possible, seems like it might be something already implemented by the API?

Thanks

like image 852
user291701 Avatar asked Feb 16 '12 02:02

user291701


2 Answers

I don't think you should use a Loader for saving data to a remote server.

Instead, use an IntentService or something similar to process a queue of "save" operations. This way, your communication with the web server can be batched, collapsed (i.e. multiple queued saves for a single item can be collapsed into one operation), and will live beyond the lifespan of your activity if need be.

A save queue processed by an IntentService (or equivalent) is also a great way to retry failed operations with backoff, since you can implement delayed retries with exponential backoff using AlarmManager.

like image 97
Roman Nurik Avatar answered Oct 17 '22 11:10

Roman Nurik


An IntentService or bound service are always good approaches for that. As Roman points, note that enqueuing several requests and called them separately is not highly recommended (it is very likely that you give a lot of work to the radio connection - when using data - which among other things drain your battery. Here is must-read about that)

I'd personally recommend to use a bound service with a queue of requests and a pool of threads available (that approach gives you full control for more complex network operations like in your case). There are more details on the approach here and a testcase working example over here.

Update us about your progress.

like image 1
Jose L Ugia Avatar answered Oct 17 '22 11:10

Jose L Ugia