Created
September 21, 2017 10:35
-
-
Save seanchas116/708c7c725e330c8887572a2c7c2eb089 to your computer and use it in GitHub Desktop.
Firebase value as custom MobX observable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Atom } from 'mobx' | |
import * as firebase from 'firebase' | |
// Custom observable for Firebase value | |
// see https://mobx.js.org/refguide/extending.html | |
export class FirebaseWatcher<T> { | |
private atom: Atom | |
private ref?: firebase.database.Reference | |
private _value: T | |
get value () { | |
if (this.atom.reportObserved()) { | |
return this._value | |
} else { | |
return this.defaultValue | |
} | |
} | |
constructor (public path: string, private defaultValue: T) { | |
this._value = defaultValue | |
this.atom = new Atom( | |
"FirebaseWatcher", | |
() => this.connect(), | |
() => this.disconnect() | |
) | |
} | |
private connect () { | |
this.ref = firebase.database().ref(this.path) | |
this.ref.on('value', snapshot => { | |
if (snapshot) { | |
this._value = snapshot.val() | |
this.atom.reportChanged() | |
} | |
}) | |
} | |
private disconnect () { | |
if (this.ref) { | |
this.ref.off() | |
this.ref = undefined | |
} | |
} | |
} | |
const watcher = new FirebaseWatcher<Foo>('foo', defaultFoo) | |
autorun(() => { | |
console.log(watcher.value) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment