Skip to main content

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.

Dart VMFlutter native✓ tested in CI
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();
}

Key points

  • Peers send changes: exportChanges on one side, importChanges on 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_sync does this exchange for you.