Skip to content

chore(firestore): add support for onSnapshotsInSync #8379

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 9 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import static io.invertase.firebase.firestore.ReactNativeFirebaseFirestoreCommon.rejectPromiseFirestoreException;
import static io.invertase.firebase.firestore.UniversalFirebaseFirestoreCommon.createFirestoreKey;
import static io.invertase.firebase.firestore.UniversalFirebaseFirestoreCommon.getFirestoreForApp;
import static io.invertase.firebase.firestore.UniversalFirebaseFirestoreCommon.getQueryForFirestore;

import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Promise;
Expand Down Expand Up @@ -193,6 +194,63 @@ public void persistenceCacheIndexManager(
promise.resolve(null);
}

@ReactMethod
public void snapshotsInSyncListener(
String appName,
String databaseId,
int listenerId
) {
FirebaseFirestore firebaseFirestore = getFirestoreForApp(appName, databaseId);
ReactNativeFirebaseFirestoreQuery firestoreQuery =
new ReactNativeFirebaseFirestoreQuery(
appName,
databaseId,
getQueryForFirestore(firebaseFirestore)
);

handleSnapshotsInSync(appName, databaseId);
}

@ReactMethod
public void onSnapshotsInSync(String appName, String databaseId, Promise promise) {
ListenerRegistration registration = FirebaseFirestore.getInstance()
.addSnapshotsInSyncListener(() -> {
WritableMap result = Arguments.createMap();
getReactApplicationContext()
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("firestore_onSnapshotsInSync", result);
});

promise.resolve(null);
}

private void handleSnapshotsInSync(
ReactNativeFirebaseFirestoreQuery firestoreQuery,
String appName,
String databaseId,
int listenerId
) {

final EventListener<QuerySnapshot> listener =
(querySnapshot, exception) -> {
if (exception != null) {
ListenerRegistration listenerRegistration = collectionSnapshotListeners.get(listenerId);
if (listenerRegistration != null) {
listenerRegistration.remove();
collectionSnapshotListeners.remove(listenerId);
}
sendOnSnapshotError(appName, databaseId, listenerId, exception);
} else {
sendOnSnapshotEvent(appName, databaseId, listenerId, querySnapshot, metadataChanges);
}
};

ListenerRegistration listenerRegistration =
firestoreQuery.query.addSnapshotListener(metadataChanges, listener);

collectionSnapshotListeners.put(listenerId, listenerRegistration);
}

private WritableMap taskProgressToWritableMap(LoadBundleTaskProgress progress) {
WritableMap writableMap = Arguments.createMap();
writableMap.putDouble("bytesLoaded", progress.getBytesLoaded());
Expand Down
68 changes: 68 additions & 0 deletions packages/firestore/e2e/DocumentReference/onSnapshotsInSync.e2e.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/*
* Copyright (c) 2016-present Invertase Limited & Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this library except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/

describe('firestore().onSnapshotsInSync() modular', function () {
if (Platform.other) return;

const { getFirestore, doc, onSnapshot, onSnapshotsInSync, setDoc } = firestoreModular;
const TEST_DOC = `${COLLECTION}/modular_sync_test`;

it('calls onSnapshotsInSync after a snapshot is delivered', async function () {
const db = getFirestore();
const docRef = doc(db, TEST_DOC);

const snapshotSpy = sinon.spy();
const syncSpy = sinon.spy();

// Set initial data
await setDoc(docRef, { foo: 'initial' });

// Subscribe to snapshot and sync
const unsubSnapshot = onSnapshot(docRef, snapshotSpy);
const unsubSync = onSnapshotsInSync(db, syncSpy);

// Trigger change
await setDoc(docRef, { foo: 'updated' });

// Wait for both
await Utils.spyToBeCalledOnceAsync(snapshotSpy);
await Utils.spyToBeCalledOnceAsync(syncSpy);

snapshotSpy.should.be.calledOnce();
syncSpy.should.be.calledOnce();

unsubSnapshot();
unsubSync();
});

it('should not fire sync after unsubscribe', async function () {
const db = getFirestore();
const syncSpy = sinon.spy();

const unsubSync = onSnapshotsInSync(db, syncSpy);
unsubSync();

await Utils.sleep(1000);

await setDoc(doc(db, `${COLLECTION}/modular_sync_test_unsub`), { foo: 'change' });

await Utils.sleep(1000);

syncSpy.should.not.be.called();
});
});

Check failure on line 68 in packages/firestore/e2e/DocumentReference/onSnapshotsInSync.e2e.js

View workflow job for this annotation

GitHub Actions / Lint

Delete `⏎`

Check failure on line 68 in packages/firestore/e2e/DocumentReference/onSnapshotsInSync.e2e.js

View workflow job for this annotation

GitHub Actions / Lint

Delete `⏎`
8 changes: 8 additions & 0 deletions packages/firestore/ios/RNFBFirestore/RNFBFirestoreModule.m
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,14 @@
resolve(nil);
}

RCT_EXPORT_METHOD(addSnapshotsInSyncListener:(RCTResponseSenderBlock)callback) {
FIRListenerRegistration *registration = [[FIRFirestore firestore]

Check failure on line 244 in packages/firestore/ios/RNFBFirestore/RNFBFirestoreModule.m

View workflow job for this annotation

GitHub Actions / iOS (debug)

use of undeclared identifier 'FIRListenerRegistration'

Check failure on line 244 in packages/firestore/ios/RNFBFirestore/RNFBFirestoreModule.m

View workflow job for this annotation

GitHub Actions / iOS (debug)

use of undeclared identifier 'registration'

Check failure on line 244 in packages/firestore/ios/RNFBFirestore/RNFBFirestoreModule.m

View workflow job for this annotation

GitHub Actions / iOS (release)

use of undeclared identifier 'FIRListenerRegistration'

Check failure on line 244 in packages/firestore/ios/RNFBFirestore/RNFBFirestoreModule.m

View workflow job for this annotation

GitHub Actions / iOS (release)

use of undeclared identifier 'registration'
addSnapshotsInSyncListener:^{
callback(@[]);
}];
}


- (NSMutableDictionary *)taskProgressToDictionary:(FIRLoadBundleTaskProgress *)progress {
NSMutableDictionary *progressMap = [[NSMutableDictionary alloc] init];
progressMap[@"bytesLoaded"] = @(progress.bytesLoaded);
Expand Down
67 changes: 67 additions & 0 deletions packages/firestore/lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
'firestore_collection_sync_event',
'firestore_document_sync_event',
'firestore_transaction_event',
'firestore_snapshots_in_sync_event',
];

class FirebaseFirestoreModule extends FirebaseModule {
Expand Down Expand Up @@ -84,6 +85,13 @@
);
});

this.emitter.addListener(this.eventNameForApp('firestore_snapshots_in_sync_event'), event => {
this.emitter.emit(

Check warning on line 89 in packages/firestore/lib/index.js

View check run for this annotation

Codecov / codecov/patch

packages/firestore/lib/index.js#L89

Added line #L89 was not covered by tests
this.eventNameForApp(`firestore_snapshots_in_sync_event:${event.listenerId}`),
event,
);
});

this._settings = {
ignoreUndefinedProperties: false,
persistence: true,
Expand Down Expand Up @@ -134,6 +142,65 @@
await this.native.terminate();
}

onSnapshot(...args) {

Check warning on line 145 in packages/firestore/lib/index.js

View check run for this annotation

Codecov / codecov/patch

packages/firestore/lib/index.js#L145

Added line #L145 was not covered by tests
let snapshotListenOptions;
let callback;
let onNext;
let onError;

try {
const options = parseSnapshotArgs(args);
snapshotListenOptions = options.snapshotListenOptions;

Check failure on line 153 in packages/firestore/lib/index.js

View workflow job for this annotation

GitHub Actions / Lint

'snapshotListenOptions' is assigned a value but never used. Allowed unused vars must match /^_/u
callback = options.callback;
onNext = options.onNext;
onError = options.onError;

Check warning on line 156 in packages/firestore/lib/index.js

View check run for this annotation

Codecov / codecov/patch

packages/firestore/lib/index.js#L151-L156

Added lines #L151 - L156 were not covered by tests
} catch (e) {
throw new Error(`firebase.firestore().doc().onSnapshot(*) ${e.message}`);

Check warning on line 158 in packages/firestore/lib/index.js

View check run for this annotation

Codecov / codecov/patch

packages/firestore/lib/index.js#L158

Added line #L158 was not covered by tests
}

function handleSuccess(documentSnapshot) {
callback(documentSnapshot, null);
onNext(documentSnapshot);

Check warning on line 163 in packages/firestore/lib/index.js

View check run for this annotation

Codecov / codecov/patch

packages/firestore/lib/index.js#L161-L163

Added lines #L161 - L163 were not covered by tests
}

function handleError(error) {
callback(null, error);
onError(error);

Check warning on line 168 in packages/firestore/lib/index.js

View check run for this annotation

Codecov / codecov/patch

packages/firestore/lib/index.js#L166-L168

Added lines #L166 - L168 were not covered by tests
}

const listenerId = _id++;

Check warning on line 171 in packages/firestore/lib/index.js

View check run for this annotation

Codecov / codecov/patch

packages/firestore/lib/index.js#L171

Added line #L171 was not covered by tests

const onSnapshotSubscription = this._firestore.emitter.addListener(

Check warning on line 173 in packages/firestore/lib/index.js

View check run for this annotation

Codecov / codecov/patch

packages/firestore/lib/index.js#L173

Added line #L173 was not covered by tests
this._firestore.eventNameForApp(`firestore_snapshots_in_sync_event:${listenerId}`),
event => {

Check warning on line 175 in packages/firestore/lib/index.js

View check run for this annotation

Codecov / codecov/patch

packages/firestore/lib/index.js#L175

Added line #L175 was not covered by tests
if (event.body.error) {
handleError(NativeError.fromEvent(event.body.error, 'firestore'));
} else {
const documentSnapshot = createDeprecationProxy(

Check warning on line 179 in packages/firestore/lib/index.js

View check run for this annotation

Codecov / codecov/patch

packages/firestore/lib/index.js#L177-L179

Added lines #L177 - L179 were not covered by tests
new FirestoreDocumentSnapshot(this._firestore, event.body.snapshot),
);
handleSuccess(documentSnapshot);

Check warning on line 182 in packages/firestore/lib/index.js

View check run for this annotation

Codecov / codecov/patch

packages/firestore/lib/index.js#L182

Added line #L182 was not covered by tests
}
},
);

const unsubscribe = () => {
onSnapshotSubscription.remove();
this._firestore.native.documentOffSnapshot(listenerId);

Check warning on line 189 in packages/firestore/lib/index.js

View check run for this annotation

Codecov / codecov/patch

packages/firestore/lib/index.js#L187-L189

Added lines #L187 - L189 were not covered by tests
};

this.firestore.native.snapshotsInSyncListener(listenerId);

Check warning on line 192 in packages/firestore/lib/index.js

View check run for this annotation

Codecov / codecov/patch

packages/firestore/lib/index.js#L192

Added line #L192 was not covered by tests

Check failure on line 193 in packages/firestore/lib/index.js

View workflow job for this annotation

GitHub Actions / Lint

Delete `····`
return unsubscribe;

Check warning on line 194 in packages/firestore/lib/index.js

View check run for this annotation

Codecov / codecov/patch

packages/firestore/lib/index.js#L194

Added line #L194 was not covered by tests
}

async onSnapshotsInSync(firestore, callback) {
this.native.onSnapshotsInSync(firestore, callback, MODULAR_DEPRECATION_ARG);
return () => {
firestoreEmitter.removeListener('onSnapshotsInSync', callback);

Check warning on line 200 in packages/firestore/lib/index.js

View check run for this annotation

Codecov / codecov/patch

packages/firestore/lib/index.js#L197-L200

Added lines #L197 - L200 were not covered by tests
};
}

useEmulator(host, port) {
if (!host || !isString(host) || !port || !isNumber(port)) {
throw new Error('firebase.firestore().useEmulator() takes a non-empty host and port');
Expand Down
25 changes: 25 additions & 0 deletions packages/firestore/lib/modular/snapshot.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,3 +227,28 @@
left: Query<AppModelType, DbModelType>,
right: Query<AppModelType, DbModelType>,
): boolean;

/**
* Attaches a listener for a snapshots-in-sync event.
* The snapshots-in-sync event indicates that all listeners affected by a given change have fired, even if
* a single server-generated change affects multiple listeners.
*
* @param firestore
* @param onSync
*/
export declare function onSnapshotsInSync(firestore: Firestore, onSync: () => void): Unsubscribe;

/**
* /**
* Attaches a listener for a snapshots-in-sync event.
* The snapshots-in-sync event indicates that all listeners affected by a given change have fired, even if
* a single server-generated change affects multiple listeners.
*
* @param firestore
* @param onSync
*/
export declare function onSnapshotsInSync(firestore: Firestore, observer: {

Check failure on line 250 in packages/firestore/lib/modular/snapshot.d.ts

View workflow job for this annotation

GitHub Actions / Lint

Replace `firestore:·Firestore,` with `⏎··firestore:·Firestore,⏎·`
next?: (value: void) => void;

Check failure on line 251 in packages/firestore/lib/modular/snapshot.d.ts

View workflow job for this annotation

GitHub Actions / Lint

Insert `··`
error?: (error: FirestoreError) => void;

Check failure on line 252 in packages/firestore/lib/modular/snapshot.d.ts

View workflow job for this annotation

GitHub Actions / Lint

Replace `··` with `····`
complete?: () => void;

Check failure on line 253 in packages/firestore/lib/modular/snapshot.d.ts

View workflow job for this annotation

GitHub Actions / Lint

Insert `··`
}): Unsubscribe;

Check failure on line 254 in packages/firestore/lib/modular/snapshot.d.ts

View workflow job for this annotation

GitHub Actions / Lint

Replace `}):·Unsubscribe;` with `··},⏎):·Unsubscribe;⏎`
3 changes: 3 additions & 0 deletions packages/firestore/lib/modular/snapshot.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
*/

import { MODULAR_DEPRECATION_ARG } from '../../../app/lib/common';
import { NativeEventEmitter, NativeModules } from 'react-native';

const emitter = new NativeEventEmitter(NativeModules.RNFBFirestoreModule);

Check failure on line 10 in packages/firestore/lib/modular/snapshot.js

View workflow job for this annotation

GitHub Actions / Lint

'emitter' is assigned a value but never used. Allowed unused vars must match /^_/u

/**
* @param {Query | DocumentReference} reference
Expand Down
Loading