Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weak Reference for Network callback bad idea?

In our project we found memory Leaks due to Network Callbacks. The Network request is fired from a fragment and the response comes back through a callback to the fragment. The issue is that when the user leaves the fragment, its not garbage collected since the callback is tied to it. Hence there is a memory Leak.

My proposed solution was to nullify the callback reference on onStop of fragment. That way, GC can take care of it.

Another solution my co worker suggested is to use to WeakReference to the callbacks. The problem with that is the callback gets garbage collected often such that we don't even get response from the callbacks (some time s when the user is waiting for a response). The problem is Weak Reference can be garbage collected using GC anytime.

I assume in this scenario, using WeakReference is not a good idea.

What do you guys think ?

like image 514
Sayooj Valsan Avatar asked Aug 27 '15 05:08

Sayooj Valsan


1 Answers

I think you shoud use weak reference for the outer class but not the callback. It's not the callback really leak but the outer class . It means that, the callback you are using is not the one that shoud be collected but the callback.

Reply me if you have any questions :)

like image 199
Mac Fang Avatar answered Oct 24 '22 14:10

Mac Fang