Weak link for network feedback is a bad idea?

In our project, we detected memory leaks due to network callbacks. The network request is launched from the fragment, and the response is returned via the fragment callback. The problem is that when the user leaves the fragment, it is not garbage collected, since the callback is bound to it. Therefore, there is a memory leak.

My suggested solution was to collapse the callback link to the onStop fragment. In this way, the GC can take care of this.

Another solution suggested by my staff member is to use for WeakReference for callbacks. The problem with this is the callback, which often collects garbage, so that we donโ€™t even get a response from the callbacks (some time when the user is waiting for an answer). The problem is that the โ€œWeak Linkโ€ can be compiled using the GC at any time.

I assume that in this case using WeakReference is not a good idea.

What do you guys think?

+5
source share
3 answers

I think you are using a weak reference for an outer class, but not a callback. This is not a callback, but a leak, but an outer class. This means that the callback you are using is not the one to be collected, but the callback.

Answer if you have questions :)

+2
source

I think that the WeakReference for the callback listener is not a good template, because you, the callback listener, can be very easy to GC and then call a callback that will never be called. However, I completely agree with the answer of @MacFang It not the callback really leak but the outer class .

+1
source

Agree with both answers. Thank you for taking the time to respond.

The solution was to wrap the "fragment" in a weak link rather than a callback, so when the network operation is completed, I check to see if the fragment is preserved. GC will garbage collect a fragment when it is not around.

0
source

All Articles