2

I am developing an application in which I am using retrofit library for calling the web services . After calling web-service a callback return Response then I am passing the Response to the next activity. I want to know the best approach for this .

I am new in memory related problems please correct me if I am totally wrong.

Shall I make a new class then pass a weak reference to that class and call the function from that class on the main activity.

Or

I shall register a new event on event bus and when the callback returns the object ,fire the event and call the function.

Please consider what is good to avoid Memory Leaks.

Nitin
  • 1,966
  • 4
  • 22
  • 53
  • Is it acceptable if the weakReference is garbage-collected in the meantime? Before the execution? – Shark Mar 30 '16 at 08:20
  • if the user is on the same screen then when the callback happens I shall take the response and take the user to the next screen. – Nitin Mar 30 '16 at 08:24

1 Answers1

7

Saving callbacks/listeners in weak references is not a good idea. See

You can "broadcast" results of asynchronous operations (Network calls in your case) on completion using event bus, and have other objects (Views, Fragments, Activities) register to event bus. Points to note:

  1. Listeners must always un-register properly, else its a memory leak.
  2. You'll need to create a new class for each event type. Soon this number will grow.
  3. Inheritance and Event bus do not play well. There is no proper "overriding" of listening methods possible.
  4. Perhaps some other object also requested the same data. Since EventBus broadcasts to all, listeners might get multiple events of same type, at unsuspected timing.

Particular to Retrofit usage, if you do requests asynchronously as:

GitHubService service = retrofit.create(GitHubService.class);

Call<List<Repo>> repos = service.listRepos("octocat");
repos.enqueue(myCallback)

Then you must remember to cancel all calls that a component has made, when the life-cycle of component is complete. I.e onDestroy() of Activity, onDetach() of Fragment, onDetachFromWindow() of View:

repos.cancel();
Community
  • 1
  • 1
S.D.
  • 29,290
  • 3
  • 79
  • 130
  • Hi I like this answer Is there any other approach to remove the memory leaks. – Nitin Mar 31 '16 at 05:59
  • 2
    @Nitin The best approach is `not to cause` memory leak. If you follow good habit of un-registering callbacks and listeners when no longer useful, tracking and canceling requests when not needed, you will be on safe side. – S.D. Mar 31 '16 at 06:47