Note: Please do not suggest FirebaseUI as an answer.
I am trying to design a chat list UI. For this, I am populating data to my recyclerview which displays the list of chat groups along with last message. I want last message to be updated in real time. Therefore, to do this, I have some listeners/subscription inside onBindViewHolder
method which continuously listen for new data and update the view.
The problem what I am facing is if the user migrates to some other activity, the app crashes when chat list data changes in the database. This is because the listeners are still running in background and trying to update views of a destroyed activity.
I am looking for a way to close my listeners/subscriptions when the recyclerview is destroyed. I have tried using onViewDetachedFromWindow
but it only works for views that get recycled when the recycler is on screen. If i was reading data only once, i would have cleaned up subscriptions as soon as they complete but my use-case is to continuously listen for changes in data.
Some sample code:
protected void onBindViewHolder(@NonNull ChatViewHolder holder,
int position, @NonNull FirebaseConversationRecord model) {
final CardView cardView = (CardView) holder.itemView;
...
final ValueEventListener listener = new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
Log.v("FIREBASEADAPTERLISTENER", dataSnapshot.getKey());
FirebaseUserRecord data = dataSnapshot.getValue(FirebaseUserRecord.class);
textViewName.setText(data.getName());
GlideApp.with(cardView.getContext())
.load(data.getProfilePicURL())
.into(imageView);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.v("FIREBASEADAPTERLISTENER", databaseError.getMessage());
}
};
...
}
EDIT
This question is in context of a RecyclerView and how to attach listeners during onBindView
. It is not the same as adding/removing a single listener from an activity which is very straight forward to implement.