TinyBase logoTinyBase

startSync

The startSync method is used to start the process of synchronization between this instance and another matching Synchronizer.

startSync(initialContent?: Content): Promise<Synchronizer>
TypeDescription
initialContent?Content

An optional Content object used when no content is available from another other peer Synchronizer instances.

returnsPromise<Synchronizer>

A Promise containing a reference to the Synchronizer object.

The underlying implementation of a Synchronizer is shared with the Persister framework, and so this startSync method is equivalent to starting both auto-loading (listening to sync messages from other active Synchronizer instances) and auto-saving (sending sync messages to it).

This method is asynchronous so you should you await calls to this method or handle the return type natively as a Promise.

Examples

This example creates two empty MergeableStore objects, creates a LocalSynchronizer for each, and starts synchronizing them. A change in one becomes evident in the other.

import {createLocalSynchronizer} from 'tinybase/synchronizers/synchronizer-local';
import {createMergeableStore} from 'tinybase';

const store1 = createMergeableStore();
const store2 = createMergeableStore();

const synchronizer1 = createLocalSynchronizer(store1);
const synchronizer2 = createLocalSynchronizer(store2);

await synchronizer1.startSync();
await synchronizer2.startSync();

store1.setTables({pets: {fido: {species: 'dog'}}});
// ...
console.log(store2.getTables());
// -> {pets: {fido: {species: 'dog'}}}

store2.setRow('pets', 'felix', {species: 'cat'});
// ...
console.log(store1.getTables());
// -> {pets: {fido: {species: 'dog'}, felix: {species: 'cat'}}}

synchronizer1.destroy();
synchronizer2.destroy();

This example creates two empty MergeableStore objects, creates a LocalSynchronizer for each, and starts synchronizing them with default content. The default content from the first Synchronizer's startSync method ends up populated in both MergeableStore instances: by the time the second started, the first was available to synchronize with and its default was not needed.

import {createLocalSynchronizer} from 'tinybase/synchronizers/synchronizer-local';
import {createMergeableStore} from 'tinybase';

const store1 = createMergeableStore();
const store2 = createMergeableStore();

const synchronizer1 = createLocalSynchronizer(store1);
const synchronizer2 = createLocalSynchronizer(store2);

await synchronizer1.startSync([{pets: {fido: {species: 'dog'}}}, {}]);
await synchronizer2.startSync([{pets: {felix: {species: 'cat'}}}, {}]);

// ...

console.log(store1.getTables());
// -> {pets: {fido: {species: 'dog'}}}
console.log(store2.getTables());
// -> {pets: {fido: {species: 'dog'}}}

synchronizer1.destroy();
synchronizer2.destroy();

Since

v5.0.0