Observables with Cloud and React
Aven Cloud uses RxJS under the hood, and enables you to use a standard pattern for observing data in your database.
Cloud values expose data through RxJS Observables such as .observeValue. These are special because they cause the doc to observe the required data from the Source, until the subscription is removed.
Subjects
A Subject is a stream of events/updates that you can subscribe to. Unlike a bare observable, several subscribers can share the same stream of events.
const message = new Subject();
message.subscribe(m => console.log(`Hello ${m}`));
message.subscribe(m => console.log(`Goodbye ${m}`));
message.next('World');
// Will log:
Hello World
Goodbye World
Behavior Subjects
Behavior subjects are RxJS observables that also have the current value available by calling `getValue()` on it.
For example, to see if a current doc is syncronized, you can check if `doc.isConnected.getValue()` is true.
Because behavior subjects are observables, you can subscribe manually via `.subscribe(`
Manual Subscription
Every observable has a "subscribe" function that you can use to get updated values, and to trigger the initial fetch. It retuns a subscriber which you can use for unsubscription.
In this case we are using "observeValue", as defined on the client doc.
const fooDoc = cloud.get('foo');
const subscription = fooDoc.observeValue.subscribe(
newFoo => {
console.log('We now know that foo is:');
console.log(JSON.stringify(foo));
}
);
// when ready to stop getting updates for foo:
subscription.unsubscribe();
React HOC
To create a component that automatically subscribes to incoming observable props, try withObservables.
React Render Prop Component
Not yet implemented.
React useObservable hook
Cloud-React comes with a hook for watching an observable or behavior subject.
function DisplayFoo() {
const cloud = useCloud();
const fooDoc = cloud.get('foo');
const fooValue = useObservable(fooDoc.observeValue);
return <Text>Current value: {JSON.stringify(fooValue)}</Text>;
}
Also see the cloud react hooks, which offer higher-level functionality than useObservable.