运行阻止请求

时间:2017-02-01 22:24:28

标签: android firebase firebase-realtime-database

我读过Firebase在后台线程上运行它的操作,以及它在UI线程上的回调。

有没有办法阻止Firebase操作?

例如:

我知道setValue()没有返回布尔值,我问是否有类似API的代码如下所示

// we are in a background thread

DatabaseReference ref = FirebaseDatabase.getInstance().getReference();

boolean success = ref.child("user").child("name").setValue("Arthur");

// code is blocked until operation completes

Log.d("MY_TAG", "successfull operation:" + success);

1 个答案:

答案 0 :(得分:2)

FirebaseDatabase API不包含setValue()的阻止形式。您可以使用返回的Task在您自己的代码中添加阻塞工作(非主)线程:

    boolean success = false;
    DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
    Task task = ref.child("user").child("name").setValue("Arthur");

    try {
        Tasks.await(task);
        success = task.isSuccessful();
    } catch (ExecutionException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    Log.d("MY_TAG", "successfull operation:" + success);

Semaphore可用于阻止读取。因为侦听器回调在主线程上运行,所以此代码只能在另一个线程上运行。如果在主线程上运行,则会死锁。

    final Semaphore sem = new Semaphore(0);

    DatabaseReference ref = FirebaseDatabase.getInstance().getReference();

    ref.child("user").child("name").addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String name = dataSnapshot.getValue(String.class);
            Log.i("MY_TAG", "Name=" + name);
            sem.release();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.e("MY_TAG", "onCancelled: " + databaseError.getMessage());
            sem.release();
        }
    });

    try {
        sem.acquire();
    } catch (InterruptedException e) {
        Log.w("MY_TAG", "Interrupted");
    }

您还可以使用Task进行阻止读取(在主线程之外):

    final TaskCompletionSource<DataSnapshot> taskSource = new TaskCompletionSource<>();
    final Task<DataSnapshot> task = taskSource.getTask();

    DatabaseReference ref = FirebaseDatabase.getInstance().getReference();

    ref.child("user").child("name").addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            taskSource.setResult(dataSnapshot);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            taskSource.setException(databaseError.toException());
        }
    });

    try {
        Tasks.await(task);

        String name = task.getResult().getValue(String.class);
        Log.i("MY_TAG", "Name=" + name);
    } catch (ExecutionException e) {
        Log.e("MY_TAG", "Read failed: " + task.getException().getMessage());
    } catch (InterruptedException e) {
        Log.w("MY_TAG", "Read interrupted");
    }