Java Code Examples for com.google.firebase.database.DatabaseReference#removeEventListener()

The following examples show how to use com.google.firebase.database.DatabaseReference#removeEventListener() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: EventTestIT.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnregisterSameCallbackTooManyTimes()
    throws InterruptedException {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp) ;

  ValueEventListener listener =
      ref.addValueEventListener(
          new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {
              // no-op
            }

            @Override
            public void onCancelled(DatabaseError error) {
              // no-op
            }
          });

  ZombieVerifier.verifyRepoZombies(ref);

  ref.removeEventListener(listener);
  ref.removeEventListener(listener);
  ZombieVerifier.verifyRepoZombies(ref);
}
 
Example 2
Source File: EventTestIT.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testSubscribeThenUnsubscribeWithoutProblemsWithLimit()
    throws InterruptedException {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp) ;

  ValueEventListener listener =
      new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {}

        @Override
        public void onCancelled(DatabaseError error) {
          fail("Should not be cancelled");
        }
      };

  ValueEventListener listenerHandle = ref.limitToLast(100).addValueEventListener(listener);
  ZombieVerifier.verifyRepoZombies(ref);
  ref.removeEventListener(listenerHandle);
  ZombieVerifier.verifyRepoZombies(ref);
  ValueEventListener listenerHandle2 = ref.limitToLast(100).addValueEventListener(listener);
  ZombieVerifier.verifyRepoZombies(ref);
  ref.removeEventListener(listenerHandle2);
  ZombieVerifier.verifyRepoZombies(ref);
}
 
Example 3
Source File: EventTestIT.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testSubscribeThenUnsubscribeWithoutProblems()
    throws InterruptedException {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp) ;

  ValueEventListener listener =
      new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {}

        @Override
        public void onCancelled(DatabaseError error) {
          fail("Should not be cancelled");
        }
      };

  ValueEventListener listenerHandle = ref.addValueEventListener(listener);
  ZombieVerifier.verifyRepoZombies(ref);
  ref.removeEventListener(listenerHandle);
  ZombieVerifier.verifyRepoZombies(ref);
  ValueEventListener listenerHandle2 = ref.addValueEventListener(listener);
  ZombieVerifier.verifyRepoZombies(ref);
  ref.removeEventListener(listenerHandle2);
  ZombieVerifier.verifyRepoZombies(ref);
}
 
Example 4
Source File: FirestackDatabase.java    From react-native-firestack with MIT License 5 votes vote down vote up
public void removeValueEventListener() {
  DatabaseReference ref = this.getDatabaseRef();
  if (mValueListener != null) {
    ref.removeEventListener(mValueListener);
    this.notListeningTo(mPath, "value");
    mValueListener = null;
  }
  if (mOnceValueListener != null) {
    ref.removeEventListener(mOnceValueListener);
    mOnceValueListener = null;
  }
}
 
Example 5
Source File: DatabaseHelper.java    From social-app-android with Apache License 2.0 5 votes vote down vote up
public void closeListener(ValueEventListener listener) {
    if (activeListeners.containsKey(listener)) {
        DatabaseReference reference = activeListeners.get(listener);
        reference.removeEventListener(listener);
        activeListeners.remove(listener);
        LogUtil.logDebug(TAG, "closeListener(), listener was removed: " + listener);
    } else {
        LogUtil.logDebug(TAG, "closeListener(), listener not found :" + listener);
    }
}
 
Example 6
Source File: FirestackDatabase.java    From react-native-firestack with MIT License 5 votes vote down vote up
public void removeChildEventListener() {
  if (mEventListener != null) {
    DatabaseReference ref = this.getDatabaseRef();
    ref.removeEventListener(mEventListener);
    this.notListeningTo(mPath, "child_added");
    this.notListeningTo(mPath, "child_changed");
    this.notListeningTo(mPath, "child_removed");
    this.notListeningTo(mPath, "child_moved");
    mEventListener = null;
  }
}
 
Example 7
Source File: DatabaseHelper.java    From social-app-android with Apache License 2.0 5 votes vote down vote up
public void closeAllActiveListeners() {
    for (ValueEventListener listener : activeListeners.keySet()) {
        DatabaseReference reference = activeListeners.get(listener);
        reference.removeEventListener(listener);
    }

    activeListeners.clear();
}
 
Example 8
Source File: DatabaseHelper.java    From social-app-android with Apache License 2.0 5 votes vote down vote up
public void closeListener(ValueEventListener listener) {
    if (activeListeners.containsKey(listener)) {
        DatabaseReference reference = activeListeners.get(listener);
        reference.removeEventListener(listener);
        activeListeners.remove(listener);
        LogUtil.logDebug(TAG, "closeListener(), listener was removed: " + listener);
    } else {
        LogUtil.logDebug(TAG, "closeListener(), listener not found :" + listener);
    }
}
 
Example 9
Source File: FirebaseIndexArray.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
@Override
protected void onDestroy() {
    super.onDestroy();
    mKeySnapshots.removeChangeEventListener(this);

    for (DatabaseReference ref : mRefs.keySet()) {
        ref.removeEventListener(mRefs.get(ref));
    }
    mRefs.clear();
}
 
Example 10
Source File: OrderByTestIT.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testRemovingDefaultListener()
    throws InterruptedException, ExecutionException, TimeoutException, TestFailure {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp) ;

  Object initialData = MapBuilder.of("key", "value");
  new WriteFuture(ref, initialData).timedGet();

  ValueEventListener listener =
      ref.orderByKey()
          .addValueEventListener(
              new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot snapshot) {}

                @Override
                public void onCancelled(DatabaseError error) {}
              });

  ref.addValueEventListener(listener);
  // Should remove both listener and should remove the listen sent to the server
  ref.removeEventListener(listener);

  // This used to crash because a listener for ref.orderByKey() existed already
  Object result = new ReadFuture(ref.orderByKey()).waitForLastValue();
  assertEquals(initialData, result);
}
 
Example 11
Source File: OrderByTestIT.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testServerRespectsKeyIndex()
    throws InterruptedException, ExecutionException, TimeoutException, TestFailure {
  List<DatabaseReference> refs = IntegrationTestUtils.getRandomNode(masterApp, 2);
  DatabaseReference writer = refs.get(0);
  DatabaseReference reader = refs.get(1);

  Map<String, Object> initial = MapBuilder.of("a", 1, "b", 2, "c", 3);
  // If the server doesn't respect the index, it will send down limited data, but with no
  // offset, so the expected and actual data don't match.
  Query query = reader.orderByKey().startAt("b").limitToFirst(2);

  new WriteFuture(writer, initial).timedGet();

  final List<String> actualChildren = new ArrayList<>();
  final Semaphore semaphore = new Semaphore(0);
  ValueEventListener valueListener =
      query.addValueEventListener(
          new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {
              for (DataSnapshot child : snapshot.getChildren()) {
                actualChildren.add(child.getKey());
              }
              semaphore.release();
            }

            @Override
            public void onCancelled(DatabaseError error) {
              Assert.fail();
            }
          });

  TestHelpers.waitFor(semaphore);
  Assert.assertEquals(ImmutableList.of("b", "c"), actualChildren);

  // cleanup
  reader.removeEventListener(valueListener);
}
 
Example 12
Source File: OrderByTestIT.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testQueriesOnLeafNodes()
    throws InterruptedException, ExecutionException, TestFailure, TimeoutException {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp) ;
  final Semaphore semaphore = new Semaphore(0);
  new WriteFuture(ref, "leaf-node").timedGet();

  final List<DataSnapshot> snapshots = new ArrayList<>();
  Query query = ref.orderByChild("foo").limitToLast(1);
  final ValueEventListener listener =
      query.addValueEventListener(
          new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {
              snapshots.add(snapshot);
              semaphore.release();
            }

            @Override
            public void onCancelled(DatabaseError error) {
              Assert.fail();
            }
          });

  TestHelpers.waitFor(semaphore);

  Assert.assertEquals(1, snapshots.size());
  Assert.assertNull(snapshots.get(0).getValue());

  // cleanup
  TestHelpers.waitForRoundtrip(ref);
  ref.removeEventListener(listener);
}
 
Example 13
Source File: OrderByTestIT.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testChildAddedEvents() throws InterruptedException {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp) ;

  Map<String, Object> initial =
      new MapBuilder()
          .put("a", MapBuilder.of("value", 5L))
          .put("c", MapBuilder.of("value", 3L))
          .build();

  final List<String> snapshotNames = new ArrayList<>();
  final List<String> prevNames = new ArrayList<>();
  final Semaphore semaphore = new Semaphore(0);
  final ChildEventListener testListener =
      ref.orderByChild("value")
          .addChildEventListener(
              new TestChildEventListener() {
                @Override
                public void onChildAdded(DataSnapshot snap, String prevName) {
                  snapshotNames.add(snap.getKey());
                  prevNames.add(prevName);
                  semaphore.release();
                }
              });

  ref.setValueAsync(initial);
  TestHelpers.waitFor(semaphore, 2);
  Assert.assertEquals(Arrays.asList("c", "a"), snapshotNames);
  Assert.assertEquals(Arrays.asList(null, "c"), prevNames);

  Map<String, Object> updates = new HashMap<>();
  updates.put("b", MapBuilder.of("value", 4));
  updates.put("d", MapBuilder.of("value", 2));
  ref.updateChildrenAsync(updates);

  TestHelpers.waitFor(semaphore, 2);
  Assert.assertEquals(Arrays.asList("c", "a", "d", "b"), snapshotNames);
  Assert.assertEquals(Arrays.asList(null, "c", null, "c"), prevNames);
  ref.removeEventListener(testListener);
}
 
Example 14
Source File: DatabaseHelper.java    From social-app-android with Apache License 2.0 5 votes vote down vote up
public void closeAllActiveListeners() {
    for (ValueEventListener listener : activeListeners.keySet()) {
        DatabaseReference reference = activeListeners.get(listener);
        reference.removeEventListener(listener);
    }

    activeListeners.clear();
}
 
Example 15
Source File: EventTestIT.java    From firebase-admin-java with Apache License 2.0 4 votes vote down vote up
@Test
public void testUnsubscribeEventsAndConfirmEventsNoLongerFire()
    throws TestFailure, ExecutionException, TimeoutException,
        InterruptedException {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp) ;

  final AtomicInteger callbackCount = new AtomicInteger(0);

  final ValueEventListener listener =
      ref.addValueEventListener(
          new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {
              if (snapshot.getValue() != null) {
                callbackCount.incrementAndGet();
              }
            }

            @Override
            public void onCancelled(DatabaseError error) {
              fail("Should not be cancelled");
            }
          });
  ZombieVerifier.verifyRepoZombies(ref);

  for (int i = 0; i < 3; ++i) {
    ref.setValueAsync(i);
  }

  TestHelpers.waitForRoundtrip(ref);
  ref.removeEventListener(listener);
  ZombieVerifier.verifyRepoZombies(ref);

  for (int i = 10; i < 13; ++i) {
    ref.setValueAsync(i);
  }

  for (int i = 20; i < 22; ++i) {
    ref.setValueAsync(i);
  }
  new WriteFuture(ref, 22).timedGet();
  assertEquals(3, callbackCount.get());
}
 
Example 16
Source File: OrderByTestIT.java    From firebase-admin-java with Apache License 2.0 4 votes vote down vote up
@Test
public void testServerRespectsValueIndex()
    throws InterruptedException, ExecutionException, TimeoutException, TestFailure, IOException {
  List<DatabaseReference> refs = IntegrationTestUtils.getRandomNode(masterApp, 2);
  DatabaseReference writer = refs.get(0);
  DatabaseReference reader = refs.get(1);

  final String indexRule = "{ \".indexOn\": \".value\"}";
  String rules = formatRules(writer, indexRule);

  uploadRules(masterApp, rules);

  Map<String, Object> initial = MapBuilder.of("a", 1, "c", 2, "b", 3);
  // If the server doesn't respect the index, it will send down limited data, but with no
  // offset, so the expected and actual data don't match.
  Query query = reader.orderByValue().startAt(2).limitToFirst(2);

  new WriteFuture(writer, initial).timedGet();

  final List<String> actualChildren = new ArrayList<>();
  final Semaphore semaphore = new Semaphore(0);
  ValueEventListener valueListener =
      query.addValueEventListener(
          new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {
              for (DataSnapshot child : snapshot.getChildren()) {
                actualChildren.add(child.getKey());
              }
              semaphore.release();
            }

            @Override
            public void onCancelled(DatabaseError error) {
              Assert.fail();
            }
          });

  TestHelpers.waitFor(semaphore);

  Assert.assertEquals(ImmutableList.of("c", "b"), actualChildren);

  // cleanup
  reader.removeEventListener(valueListener);
}
 
Example 17
Source File: EventTestIT.java    From firebase-admin-java with Apache License 2.0 4 votes vote down vote up
@Test
public void testRegisterTheSameCallbackMultipleTimes()
    throws TestFailure, ExecutionException, TimeoutException, InterruptedException {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp) ;

  final AtomicInteger callbackCount = new AtomicInteger(0);
  ValueEventListener listener =
      new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
          if (snapshot.getValue() != null) {
            callbackCount.incrementAndGet();
          }
        }

        @Override
        public void onCancelled(DatabaseError error) {
          fail("Should not be cancelled");
        }
      };

  ref.addValueEventListener(listener);
  ref.addValueEventListener(listener);
  ref.addValueEventListener(listener);
  ZombieVerifier.verifyRepoZombies(ref);

  new WriteFuture(ref, 42).timedGet();
  assertEquals(3, callbackCount.get());

  ref.removeEventListener(listener);
  new WriteFuture(ref, 84).timedGet();
  assertEquals(5, callbackCount.get());
  ZombieVerifier.verifyRepoZombies(ref);

  ref.removeEventListener(listener);
  new WriteFuture(ref, 168).timedGet();
  assertEquals(6, callbackCount.get());
  ZombieVerifier.verifyRepoZombies(ref);

  ref.removeEventListener(listener);
  new WriteFuture(ref, 376).timedGet();
  assertEquals(6, callbackCount.get());
  ZombieVerifier.verifyRepoZombies(ref);
}
 
Example 18
Source File: QueryTestIT.java    From firebase-admin-java with Apache License 2.0 4 votes vote down vote up
@Test
public void testAddingListensForTheSamePathDoesNotCheckFail() throws Throwable {
  // This bug manifests itself if there's a hierarchy of query listener,
  // default listener and
  // one-time listener underneath. During one-time listener registration,
  // sync-tree traversal
  // stopped as soon as it found a complete server cache (this is the case
  // for not indexed query
  // view). The problem is that the same traversal was looking for a
  // ancestor default view, and
  // the early exit prevented from finding the default listener above the
  // one-time listener. Event
  // removal code path wasn't removing the listener because it stopped as
  // soon as it found the
  // default view. This left the zombie one-time listener and check failed
  // on the second attempt
  // to create a listener for the same path (asana#61028598952586).

  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);
  final Semaphore semaphore = new Semaphore(0);

  ValueEventListener dummyListen = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot snapshot) {
      semaphore.release();
    }

    @Override
    public void onCancelled(DatabaseError error) {
    }
  };

  ref.child("child").setValueAsync(TestHelpers.fromJsonString("{\"name\": \"John\"}"));

  ref.orderByChild("name").equalTo("John").addValueEventListener(dummyListen);
  ref.child("child").addValueEventListener(dummyListen);
  TestHelpers.waitFor(semaphore, 2);

  ref.child("child").child("favoriteToy").addListenerForSingleValueEvent(dummyListen);
  TestHelpers.waitFor(semaphore, 1);

  ref.child("child").child("favoriteToy").addListenerForSingleValueEvent(dummyListen);
  TestHelpers.waitFor(semaphore, 1);

  ref.removeEventListener(dummyListen);
  ref.child("child").removeEventListener(dummyListen);
}
 
Example 19
Source File: OrderByTestIT.java    From firebase-admin-java with Apache License 2.0 4 votes vote down vote up
@Test
public void testUpdatesForUnindexedQuery()
    throws InterruptedException, ExecutionException, TestFailure, TimeoutException {
  List<DatabaseReference> refs = IntegrationTestUtils.getRandomNode(masterApp, 2);
  final DatabaseReference reader = refs.get(0);
  final DatabaseReference writer = refs.get(1);

  final List<DataSnapshot> snapshots = new ArrayList<>();

  Map<String, Object> value = new HashMap<>();
  value.put("one", new MapBuilder().put("index", 1).put("value", "one").build());
  value.put("two", new MapBuilder().put("index", 2).put("value", "two").build());
  value.put("three", new MapBuilder().put("index", 3).put("value", "three").build());

  new WriteFuture(writer, value).timedGet();

  final Semaphore semaphore = new Semaphore(0);

  Query query = reader.orderByChild("index").limitToLast(2);
  final ValueEventListener listener =
      query.addValueEventListener(
          new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {
              snapshots.add(snapshot);
              semaphore.release();
            }

            @Override
            public void onCancelled(DatabaseError error) {
              Assert.fail();
            }
          });

  TestHelpers.waitFor(semaphore);

  Assert.assertEquals(1, snapshots.size());

  Map<String, Object> expected1 = new HashMap<>();
  expected1.put("two", new MapBuilder().put("index", 2L).put("value", "two").build());
  expected1.put("three", new MapBuilder().put("index", 3L).put("value", "three").build());
  Assert.assertEquals(expected1, snapshots.get(0).getValue());

  // update child which should trigger value event
  writer.child("one/index").setValueAsync(4);
  TestHelpers.waitFor(semaphore);

  Assert.assertEquals(2, snapshots.size());
  Map<String, Object> expected2 = new HashMap<>();
  expected2.put("three", new MapBuilder().put("index", 3L).put("value", "three").build());
  expected2.put("one", new MapBuilder().put("index", 4L).put("value", "one").build());
  Assert.assertEquals(expected2, snapshots.get(1).getValue());

  // cleanup
  TestHelpers.waitForRoundtrip(reader);
  reader.removeEventListener(listener);
}
 
Example 20
Source File: OrderByTestIT.java    From firebase-admin-java with Apache License 2.0 4 votes vote down vote up
@Test
public void testUseFallbackThenDefineIndex()
    throws InterruptedException, ExecutionException, TimeoutException, TestFailure, IOException {

  DatabaseReference writer = IntegrationTestUtils.getRandomNode(masterApp) ;
  DatabaseReference readerReference = FirebaseDatabase.getInstance(masterApp).getReference();
  DatabaseReference reader = readerReference.child(writer.getPath().toString());

  Map<String, Object> foo1 =
      TestHelpers.fromJsonString(
          "{ "
              + "\"a\": {\"order\": 2, \"foo\": 1}, "
              + "\"b\": {\"order\": 0}, "
              + "\"c\": {\"order\": 1, \"foo\": false}, "
              + "\"d\": {\"order\": 3, \"foo\": \"hello\"} }");

  new WriteFuture(writer, foo1).timedGet();

  final List<DataSnapshot> snapshots = new ArrayList<>();
  final Semaphore semaphore = new Semaphore(0);
  Query query = reader.orderByChild("order").limitToLast(2);
  final ValueEventListener listener =
      query.addValueEventListener(
          new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {
              snapshots.add(snapshot);
              semaphore.release();
            }

            @Override
            public void onCancelled(DatabaseError error) {
              Assert.fail();
            }
          });

  TestHelpers.waitFor(semaphore);

  Assert.assertEquals(1, snapshots.size());
  Map<String, Object> expected = MapBuilder.of(
      "d", MapBuilder.of("order", 3L, "foo", "hello"),
      "a", MapBuilder.of("order", 2L, "foo", 1L));
  Assert.assertEquals(expected, snapshots.get(0).getValue());

  uploadRules(masterApp, formatRules(reader, "{ \".indexOn\": \"order\" }"));

  Map<String, Object> fooE = TestHelpers.fromJsonString("{\"order\": 1.5, \"foo\": true}");
  new WriteFuture(writer.child("e"), fooE).timedGet();
  TestHelpers.waitForRoundtrip(reader);

  Map<String, Object> fooF =
      TestHelpers.fromJsonString("{\"order\": 4, \"foo\": {\"bar\": \"baz\"}}");
  new WriteFuture(writer.child("f"), fooF).timedGet();
  TestHelpers.waitForRoundtrip(reader);

  TestHelpers.waitFor(semaphore);
  Assert.assertEquals(2, snapshots.size());

  Map<String, Object> expected2 =
      new MapBuilder()
          .put(
              "f",
              new MapBuilder()
                  .put("order", 4L)
                  .put("foo", MapBuilder.of("bar", "baz"))
                  .build())
          .put("d", MapBuilder.of("order", 3L, "foo", "hello"))
          .build();
  Assert.assertEquals(expected2, snapshots.get(1).getValue());

  // cleanup
  TestHelpers.waitForRoundtrip(reader);
  reader.removeEventListener(listener);
}