Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a timeout to a Firebase Database read query

I'm trying to make a read query timeout with Firebase Database when there is no internet connection or any other problem. The problem is that even when the timeout takes effect and the listener is removed, it still gets called even though it has been removed. How can I prevent that? What's the best way to handle timeout?

Here's my code :

final DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("key");
final ValueEventListener listener = new ValueEventListener() { /* ... */ };
ref.addListenerForSingleValueEvent(listener);

Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        ref.removeEventListener(listener);
    }
}, 5000);

Someone here seems to have the same issue but I don't understand the solution.

like image 808
Nicolas Avatar asked May 12 '17 21:05

Nicolas


1 Answers

There is nothing like timeout in the Firebase API, hence timeouts should be handled using our own logic. This is how i implement timeouts in my code.

    private void getDataFromFirebase()
    {
        final boolean[] gotResult = new boolean[1];
        gotResult[0] = false;

        FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
        DatabaseReference dataReference = firebaseDatabase.getReference().child("data");

        ValueEventListener dataFetchEventListener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                gotResult[0] = true;
                // You async code goes here
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                gotResult[0] = true;
            }
        };

        if(isNetworkAvailable()) {

            dataReference.addListenerForSingleValueEvent(dataFetchEventListener);
            Timer timer = new Timer();
            TimerTask timerTask = new TimerTask() {
                @Override
                public void run() {
                    timer.cancel();
                    if (gotResult[0] == false) { //  Timeout
                        dataReference.removeEventListener(dataFetchEventListener);
                        // Your timeout code goes here
                    }
                }
            };
            // Setting timeout of 10 sec to the request
            timer.schedule(timerTask, 10000L);
        }
        else{
            // Internet not available
        }
    }
like image 98
Parag Kadam Avatar answered Nov 05 '22 16:11

Parag Kadam