Two peers, one result
The smallest CRDT program: two peers, one text, two edits made at the same time with no connection, and one merged result on both sides.
Two peers, one resultSource ↗
Two documents edit one text at the same time, with no connection. They exchange their changes and both read the same text.
- main.dart
- Install
import 'dart:io';
import 'package:crdt_lf/crdt_lf.dart';
/// Lets two peers edit one text at the same time, and returns what each reads.
(String, String) mergeTwoPeers() {
final alice = CRDTDocument();
final bob = CRDTDocument();
// The same handler id on both peers: it is the same text.
final aliceText = CRDTFugueTextHandler(alice, 'note');
final bobText = CRDTFugueTextHandler(bob, 'note');
aliceText.insert(0, 'Hello world');
bob.importChanges(alice.exportChanges()); // Bob now reads "Hello world"
// Both edit at the same time, with no connection.
aliceText.insert(0, 'Big ');
bobText.insert(11, '!');
// They meet again and exchange what the other is missing.
bob.importChanges(alice.exportChanges());
alice.importChanges(bob.exportChanges());
stdout
..writeln(aliceText.value) // Big Hello world!
..writeln(bobText.value); // Big Hello world!
final result = (aliceText.value, bobText.value);
alice.dispose();
bob.dispose();
return result;
}
void main() {
mergeTwoPeers();
}
dart pub add crdt_lf
Key points
- Peers send changes:
exportChangeson one side,importChangeson the other. - Importing the same change twice does nothing, so a peer can send everything it has.
- Every peer creates the handler under the same id (
note): that id is what makes it the same text. - In an app,
crdt_socket_syncdoes this exchange for you.