3

Recently I came across a blog which talks about avoiding weak reference in android-https://medium.com/google-developer-experts/weakreference-in-android-dd1e66b9be9d

Currently, the project I am working on follows MVP architecture and we use weak references(for listeners) in presenters for various callbacks events.However, I am looking for alternate ways instead of using weak references. ..probably a better way I can design my application architecture to avoid such memory leak issues. The Question here is:-

Is the current approach which I am using i.e using weak references for various listeners in presenter harmful...??If so..than how I can solve this problem in a much better way.?

1 Answers1

3

Is the current approach which I am using i.e using weak references for various listeners in presenter harmful...??

Maybe. It's difficult to say concretely without digging into your codebase. With that being said, you need to take into account the general downside of using WeakReferences. I'll point you to another StackOverflow answer that makes it clear:

... using WeakReference not just solve one problem ("I should keep in mind to not forget to remove added listener somewhere"), but also rise another -- "I should keep in mind what my listener ca stop listen in any moment when where is no more reference to it". You not solve problem, you just trade one problem for another. Look, in any way you've forced to clearly define, design and trace livespan of you listener -- one way or another.


If so..than how I can solve this problem in a much better way.?

Slowly start picking at your usage of WeakReferences. Remove them. Use the lifecycle events provided by Android to your benefit and attach, detach at the correct times. Lastly, add LeakCanary to your toolbox. Using this, screw around with the lifecycle for your various Activities and Fragments to see when and where leaks are being created.

Community
  • 1
  • 1
asadmshah
  • 1,338
  • 9
  • 7