Reputation: 15082
I have a ViewHolder
that registers as a receiver for the LocalBroadcastManager
.
The ViewHolder
also has a delegate to the Activity
that holds the RecyclerView
.
This causes a memory leak, because I can't manage to unregister the broadcast manager in the view holder when the activity is destroyed.
public class MyHolder extends RecyclerView.ViewHolder {
public interface Delegate {
...
}
private @Nullable Delegate delegate;
public MyHolder(@NonNull View itemView) {
super(itemView);
}
public void bind(@NonNull Delegate delegate) {
this.delegate = delegate;
registerNotifications();
}
public void recycle() {
unregisterNotifications();
delegate = null;
}
private void registerNotifications() {
LocalBroadcastManager.getInstance(App.getInstance().getApplicationContext()).registerReceiver(broadcastReceiver, new IntentFilter(MyFilter));
}
private void unregisterNotifications() {
LocalBroadcastManager.getInstance(App.getInstance().getApplicationContext()).unregisterReceiver(broadcastReceiver);
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
...
}
};
}
I tried to call recycle
in the RecyclerView.Adapter
's onViewDetachedFromWindow
and onViewRecycled
. But it seems that there is no guarantee that any of these will be called when the activity is destroyed.
How can I make sure that the broadcast receiver is unregistered properly when the activity is destroyed or the ViewHolder is recycled?
Upvotes: 0
Views: 360