首页 > 解决方案 > Is possible to use the instance ValueEventListener for two different calls with addValueEventListener, at same Activity?

问题描述

I'm using the method addValueEventListener as shown below:

public List<MyClassModel> DoRequestCards() {

        valueEventListener = getDatabaseReference()
                .child("Example")
                .child(Objects.requireNonNull(getFirebaseAuthInstance().getCurrentUser()).getUid())
                .addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                        list.clear();
                        for (DataSnapshot data : dataSnapshot.getChildren()) {
                            MyClassModel model = data.getValue(MyClassModel.class);
                            //Retrieves UniqueKey from each example
                            Objects.requireNonNull(card).setUniqueId(data.getKey());
                            list.add(model);
                        }
                        taskListener.OnSuccess(); //call interface method
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError databaseError) {
                        taskListener.OnError(databaseError.getMessage()); //call interface method
                    }
                });

        return list;
    }

It's possible to create another method to retrieve different list with different data fetching again addValueEventListener at same valueEventListener instance ? Or should I create another instance to it (because they're at same activity and need each to stay listening their changes) ?

I'm using the same instance of ValueEventListener at different activities, but when activity stops (onStop) I remove it (I've no problems with that).

标签: javaandroidfirebasefirebase-realtime-database

解决方案


您可以使用相同的侦听器两次。这不是问题。您可以在侦听器中检查哪个位置触发了侦听器的快照。


推荐阅读