Search code examples
androidandroid-loadermanager

Loader and LoaderManager - how to determine if a current Loader is active and running?


How can you query a LoaderManager to see if a Loader is currently running?


Solution

  • There are two possible situations of doing it:

    1st case

    If you use the only Loader or you have several but you don't care which one of them is running:

    getSupportLoaderManager().hasRunningLoaders()
    

    2nd case

    You want to know whether some particular Loader is running. It seems it's not supported by SDK, but you can easily implement it on your own.

    a) Just add the flag

    public class SomeLoader extends AsyncTaskLoader<String[]> {
    
        public boolean isRunning;
    
        @Override
        protected void onStartLoading() {
            isRunning = true;
            super.onStartLoading();
            //...
            forceLoad();
        }
    
        @Override
        public void deliverResult(String[] data) {
            super.deliverResult(data);
            isRunning = false;
        }
        //...
    }
    

    b) and use it (a bit tricky) :-)

    SomeLoader loader = (SomeLoader) manager.<String[]>getLoader(ID);
    Log.d(TAG, "isRunning: " + loader.isRunning);
    

    The key reason I have posted it here - it's a tricky enough call of a generic method before casting a Loader to your SomeLoader.

    Reminder

    Whatever you do if you call getSupportLoaderManager.restartLoader your current task (if it's running) is not being killed. So the next step will be a call of onCreateLoader which will create a new Loader. So it means that you can have 2,3,4,5 and more the same tasks parallel tasks together (if you don't prevent it in some way) that can lead to a battery draining and an exceed CPU/network load.