3

I use class which extended Loader. How can I stop my loader after I get result?

When I rotate phone I get result again:

@Override
public void onLoadFinished(Loader<Data> loader, Data data) {
      makeWorkWithData();
      //... finish this loader? (or delete result)
}
Artem
  • 4,569
  • 12
  • 44
  • 86
  • Where do you init your Loader ? – David Apr 27 '16 at 14:40
  • @David in onCreateView on my Fragment – Artem Apr 27 '16 at 14:41
  • Okay what I have done, but its not the best solution I think is, that in onLoadFinished I asign the result into an object within my activity/fragment ... then in onCreate/onCreateView I check for the resultData. If it is null I init my loader, else I leave it as it is. But you have to save the result in onSaveInstanceState and retain it in onCreate... – David Apr 27 '16 at 14:45

2 Answers2

6

Use this:

@Override
public void onLoadFinished(Loader<Data> loader, Data data) {
      makeWorkWithData();
      stopLoader(id);
} 

void stopLoader(int id) {
     getLoaderManager().destroyLoader(id);
}

And when need make request again call getLoaderManager().restartLoader()...

MyNameIs
  • 832
  • 1
  • 8
  • 19
  • Somehow my loaders is still getting called when the dataset changes, even after I called `getLoaderManager().destroyLoader(id);`. I wonder why this is happening. – Mauker Jul 15 '17 at 15:26
1

I was quit unsatisfied with Androids Loaders API as rotation will cause Loaders to restart the work they where doing. That's why I use, and created, the Android Retainable Tasks library. It's lightweight and based on the Android AsyncTask API but with automatic rotation handling. You might want to check it out and use it instead of Loaders.

https://github.com/NeoTech-Software/Android-Retainable-Tasks

Disclaimer: I'm the author of Android Retainable Tasks.

Rolf ツ
  • 8,611
  • 6
  • 47
  • 72
  • I dont know why your loaders restarted when yout rotate device. My loader doesn't restart but if my loader already get data from network - he return me this data always when I rotate device. – Artem Apr 28 '16 at 06:53
  • Some do, depending on their state (cached, running, finished). See for example: http://stackoverflow.com/a/30778505/1052697 – Rolf ツ Apr 28 '16 at 07:38
  • It would depend on if you are recreating on rotation state change. If the activity is re-created, so is the loader, and it *has* to restart and reload. – Jeffrey Blattman Aug 13 '18 at 19:02