Skip to content

Instantly share code, notes, and snippets.

@reimertz
Created November 18, 2019 05:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reimertz/ef2960319509865507130d60050dcebe to your computer and use it in GitHub Desktop.
Save reimertz/ef2960319509865507130d60050dcebe to your computer and use it in GitHub Desktop.
rxjs-firestore.js
import { Observable, interval, combineAll, combineLatest } from 'rxjs'
import { zip, startWith, timeInterval } from 'rxjs/operators'
import { useEffect, useState } from 'react'
import RNFirebase from '@react-native-firebase/app'
export const docData = doc => {
const data = doc.data()
const idKey = data && data.id ? 'firebaseId' : 'id'
return {
...data,
[idKey]: doc.id, // if original data contains an id..
}
}
export const ObservableFromRef = ref => {
return new Observable(subscriber => {
const unsubscribe = ref.onSnapshot(snapshot => subscriber.next(snapshot))
return () => unsubscribe()
})
}
export const ObservableFromAuthState = auth => {
return new Observable(subscriber => {
const unsubscribe = auth.onAuthStateChanged(user => subscriber.next(user))
return () => unsubscribe()
})
}
export const updateObservableEveryXSeconds = (observable, seconds) => {
return combineLatest(
observable,
interval(seconds * 1000).pipe(
startWith(-1),
timeInterval()
),
(observable, interval) => {
return observable
}
)
}
export const useStream = (stream, initialValue = null) => {
const [current, setCurrent] = useState(initialValue)
useEffect(() => {
const sub = stream.subscribe(setCurrent)
return () => sub.unsubscribe()
}, [])
return current
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment