Skip to content

Instantly share code, notes, and snippets.

@jesselima
Forked from deltaepsilon/rxjs-firebase-demo.js
Created April 24, 2018 01:01
Show Gist options
  • Save jesselima/fab61d7976f0a43e2bd48d99e2ea55fa to your computer and use it in GitHub Desktop.
Save jesselima/fab61d7976f0a43e2bd48d99e2ea55fa to your computer and use it in GitHub Desktop.
Demo RxJs integration with Firebase
var Rx = require('rxjs');
var firebase = require('firebase');
firebase.initializeApp({
"databaseURL": "https://quiver-two.firebaseio.com",
"serviceAccount": "./service-account.json"
});
var ref = firebase.database().ref('rxjs-demo');
Rx.Observable.fromPromise(ref.remove())
.map(function () {
return Rx.Observable.interval(2000);
})
.combineAll()
.map(function() {
return Rx.Observable.from(ref.limitToLast(1).once('value'));
})
.mergeAll()
.subscribe(function (snap) {
var random = Math.random();
var keys = Object.keys(snap.val() || {});
switch (true) {
case (!keys.length || random < 0.5) && keys.length <= 5:
Rx.Observable.fromPromise(ref.push({
random: random
}))
.subscribe(function () {
console.log('pushed');
});
break;
case keys.length > 5 || random < .75:
Rx.Observable.fromPromise(snap.ref.child(keys[0]).remove())
.subscribe(function () {
console.log('removed');
});
break;
default:
Rx.Observable.fromPromise(snap.ref.child(keys[0]).child('random').set(random))
.subscribe(function () {
console.log('changed');
});
break;
}
});
Rx.Observable.fromEvent(ref, 'child_added').subscribe(function (snap) {
console.log('child_added', snap.key);
});
Rx.Observable.fromEvent(ref, 'child_changed').subscribe(function (snap) {
console.log('child_changed', snap.key);
});
Rx.Observable.fromEvent(ref, 'child_removed').subscribe(function (snap) {
console.log('child_removed', snap.key);
});
// Rx.Observable.fromEvent(ref, 'value').subscribe(function(snap) {
// console.log('value', snap.key, snap.val());
// });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment