MobX 4, Firebase, Websockets, and You
In a previous article, I discussed how to use MobX atom
s to make your observables become observer-aware. This introduced the concepts of an observable becoming observed, and becoming unobserved, and using these events in order to set up or tear down a data stream.
Today I learned the wonderful MobX 4.x release has made all such work redundant, which is a lovely thing indeed!
MobX and You
MobX 4 introduces a swathe of new features, but amongst them are two incredible hooks for allowing more power over your resource management. These are onBecomeObserved
and onBecomeUnobserved
. These hooks let us set up event listeners for when an observable entity starts/stops being watched by some observer component, which can let us resume or suspend a realtime data stream — like a Firebase DB connection, or an open Websocket!
Here’s how (shown in Typescript, just remove types for pure JS):
import { onBecomeObserved, onBecomeUnobserved } from 'mobx'
import { observable, decorate } from "mobx";class AutoObservable<T> {
data: T
constructor(onObserved: () => void, onUnobserved: () => void) {
onBecomeObserved(this, 'data', onObserved)
onBecomeUnobserved(this, 'data', onUnobserved)
}
}decorate(AutoObservable, {
data: observable
})
The above defines a generic class definition, that takes two handlers in its constructor which will be responsible for opening and closing the realtime data stream. The decorate
method allows using the @observable
decorator, but without actually having experimental decorator support enabled.
Then, to implement the AutoObservable
, we use:
var autoObservable: AutoObservable<number>
var socket: Websocketconst openStream = () => {
socket = new Websocket("ws://localhost:8080")
socket.on("message", message => { autoObservable.data = message })
}const closeStream = () => { socket.close() }autoObservable = new AutoObservable(openStream, closeStream);
And that’s that. Replace “Websocket” with “Firestore Listener” or any other realtime datasource and you’ve got yourself a self-managing data object that opens and closes its datasource only when it becomes observed/unobserved. Like magic.