rework provider combination demo

This commit is contained in:
Kevin Jahns 2020-05-18 18:04:04 +02:00
parent 05dde1db01
commit 06048b87ee

View File

@ -149,50 +149,46 @@ the API docs.
### Example: Using and combining providers ### Example: Using and combining providers
The most common way to combine providers is probably Any Yjs providers can be combined with each other. So you can sync data over different
to combine some network provider with the local indexeddb provider: network technologies.
In most cases you want to use a networking provider (like y-webrtc or y-webrtc) in combination with a
persistence provider (y-indexeddb in the browser). Persistence allows you to load the document faster and
to sync persist data that is created while offline.
For the sake of this demo we combine two different network providers with a persistence provider.
```js ```js
import * as Y from 'yjs' import * as Y from 'yjs'
import { WebrtcProvider } from 'y-webrtc' import { WebrtcProvider } from 'y-webrtc'
import { WebsocketProvider } from 'y-websocket'
import { IndexeddbPersistence } from 'y-indexeddb' import { IndexeddbPersistence } from 'y-indexeddb'
async function main() {
const ydoc = new Y.Doc() const ydoc = new Y.Doc()
// this allows you to instantly get the (cached) documents data // this allows you to instantly get the (cached) documents data
let idbP = new IndexeddbPersistence('count-demo', ydoc) const indexeddbProvider = new IndexeddbPersistence('count-demo', ydoc)
await idbP.whenSynced idbP.whenSynced.then(() => {
console.log('loaded data from indexed db')
})
// this will sync between clients in the background, // Sync clients with the y-webrtc provider.
// may be replaced by any network provider const webrtcProvider = new WebrtcProvider('count-demo', ydoc)
let webP = new WebrtcProvider('count-demo', ydoc)
webP.connect() // Sync clients with the y-websocket provider
const websocketProvider = new WebsocketProvider('wss://demos.yjs.dev', 'count-demo', ydoc)
// array of numbers which produce a sum // array of numbers which produce a sum
const yarray = ydoc.getArray('count') const yarray = ydoc.getArray('count')
// add 1 to the sum
yarray.push([1])
// observe changes of the sum // observe changes of the sum
yarray.observe(event => { yarray.observe(event => {
// this will print updates from the network // this will print updates from the network
console.log("new sum: " + yarray.toArray().reduce((a,b)=>(a+b))) console.log("new sum: " + yarray.toArray().reduce((a,b)=>(a+b)))
}) })
// print initial number (the cached one plus one) // add 1 to the sum
let sum = yarray.toArray().reduce((a,b)=>(a+b)) yarray.push([1]) // => "new sum: 1"
console.log(sum)
}
main()
```
Example output:
```bash
32 # stored sum from indexeddb (with 1 already added to it)
new sum: 38 # delayed new sum fetched from network
``` ```
## API ## API