Sync Client
How to create an ObjectBox Sync client and connect to an ObjectBox Sync server.

ObjectBox Sync enabled library

The standard ObjectBox (database) library does not include an ObjectBox Sync implementation. Depending on the programming language, it will include the Sync API, but not the implementation. For example, ObjectBox Java in its standard version allows compiling using the Sync API, it won't any Sync logic due to the missing implementation.
If you haven't used ObjectBox before, please also be aware of documentation for the standard (non-sync) edition of ObjectBox for your programming language (Java/Kotlin, Swift, C and C++, Go). You are currently looking at the documentation specific to ObjectBox Sync, which does not cover ObjectBox basics.
By now, you were likely in touch with the ObjectBox team and have access to Sync Server and potentially a special Sync Client version. For some platforms, we maintain packages that you can include as dependencies.
Java/Kotlin (Gradle)
Swift
Flutter
Dart
C/C++
Go
Others
Version 3.0.1 has some important bug fixes for Sync, we recommend to update to this version.
Please follow the standard setup instructions. Then you can switch to the sync edition:
1
// This will try to add the native dependency automatically:
2
apply plugin: "io.objectbox.sync" // instead of "io.objectbox"
Copied!
On Android you might have to add the Sync variant of the objectbox-android library manually to the dependencies block:
1
implementation("io.objectbox:objectbox-sync-android:$objectboxVersion")
Copied!
This gives you specific information about how to get the Sync-enabled version of ObjectBox. Please also check our general installation and update docs for in-depth information.
We may distribute ObjectBox Sync for Swift in our Cocoapods staging repository (we let you know). In that case, these are some typical lines to put in your Podfile (please check the version, there might be a newer one available):
1
source https://github.com/objectbox/objectbox-swift-spec-staging.git
2
3
target 'MyCoolSyncProject' do
4
use_frameworks!
5
6
pod 'ObjectBox', '1.5.0-sync-rc5'
7
end
8
Copied!
1
dependencies:
2
objectbox: ^0.15.0
3
# use objectbox_sync_flutter_libs instead of objectbox_flutter_libs
4
objectbox_sync_flutter_libs: any
Copied!
In android/app/build.gradle set minSdkVersion 21 in section android -> defaultConfig
Add dependency to your pubspec.yaml file as usual:
1
dependencies:
2
objectbox: ^0.15.0
Copied!
To install ObjectBox Sync variant of the native library, pass --sync argument to the script:
1
bash <(curl -s https://raw.githubusercontent.com/objectbox/objectbox-dart/main/install.sh) --sync
Copied!
1
bash <(curl -s https://raw.githubusercontent.com/objectbox/objectbox-c/main/download.sh) --sync
Copied!
Or use CMake's FetchContent to get ObjectBox headers and library ready to use in your project:
CMakeLists.txt
1
include(FetchContent)
2
FetchContent_Declare(
3
objectbox
4
GIT_REPOSITORY https://github.com/objectbox/objectbox-c.git
5
GIT_TAG v0.14.0
6
)
7
8
FetchContent_MakeAvailable(objectbox)
9
10
add_executable(myapp main.cpp)
11
target_link_libraries(myapp objectbox-sync)
Copied!
1
bash <(curl -s https://raw.githubusercontent.com/objectbox/objectbox-go/main/install.sh) --sync
Copied!
Please reach out to the ObjectBox team
Now it's time to verify the setup using a flag telling if Sync is available; for example, simply log the result:
Java
Kotlin
Swift
Dart/Flutter
C++
C
Go
Others
1
import io.objectbox.sync.Sync;
2
3
String syncAvailable = Sync.isAvailable() ? "available" : "unavailable";
4
System.out.println("ObjectBox Sync is " + syncAvailable);
Copied!
1
import io.objectbox.sync.Sync
2
3
val syncAvailable = if (Sync.isAvailable()) "available" else "unavailable"
4
Log.d(App.TAG, "ObjectBox Sync is $syncAvailable")
Copied!
1
Sync.isAvailable()
Copied!
1
Sync.isAvailable()
Copied!
1
obx::Sync::isAvailable()
Copied!
1
obx_has_feature(OBXFeature_Sync)
Copied!
1
objectbox.SyncIsAvailable()
Copied!
1
// Depending on the platform something like:
2
Sync.isAvailable()
Copied!

Enable your Objects for ObjectBox Sync

ObjectBox Sync allows you to define which objects are synced and which are not. This is done at an object type level (a "class" in many programming languages). By default, an object (type) is local only: objects are kept in the database on the local device and do not get synced to other devices.
To enable sync for an object type, you add a "sync" annotation to the type definition. This is typically the entity source file, or, if you are using ObjectBox Generator, the FlatBuffers schema file:
Java
Kotlin
Swift
Dart/Flutter
C/C++ (using Generator)
Go
1
@Sync
2
@Entity
3
public class User {
4
// ...
5
}
Copied!
1
@Sync
2
@Entity
3
data class User(
4
// ...
5
)
Copied!
1
// objectbox: sync
2
class User: Entity {
3
...
4
}
Copied!
1
@Entity
2
@Sync
3
class User {
4
...
5
}
Copied!
1
/// objectbox: sync
2
table User {
3
...
4
}
Copied!
1
// `objectbox:"sync"`
2
type User struct {
3
// ...
4
}
Copied!
At this point, it is not allowed to change a non-synced object type to a synced one. This would raise questions on how to handle pre-existing data, e.g. should it be deleted, synced (how exactly? using how many transactions? ...), or kept locally until objects are put again? We welcome your input on your use case.
Additionally, there may only be relations between sync-enabled or non-sync entities, not across the boundary.
If you already have a non-synced type that you now want to sync (see also the info box above), these are the typical options you have:
  1. 1.
    If you are still in development, add the sync annotation and wipe your database(s) to start fresh with that new data model
  2. 2.
    "Replace" the entity type using a new UID (check schema changes docs for the ObjectBox binding you are using). You can keep the type name; to ObjectBox it will be a different type as the UID is different. This will delete all existing data in that type.
  3. 3.
    Have a second, synced, object type and migrate your data in your code following your rules.

Start the Sync Client

Create a Sync client for your Store and start it. It connects to a given sync server URL using some form of credentials to authenticate with the server. A minimal setup can look like this:
Java
Kotlin
Swift
Dart/Flutter
C++
C
Go
1
SyncClient syncClient = Sync.client(
2
boxStore,
3
"ws://127.0.0.1" /* Use wss for encrypted traffic. */,
4
SyncCredentials.none()
5
).buildAndStart(); // Connect and start syncing.
Copied!
1
val syncClient = Sync.client(
2
boxStore,
3
"ws://127.0.0.1" /* Use wss for encrypted traffic. */,
4
SyncCredentials.none()
5
).buildAndStart() // Connect and start syncing.
Copied!
1
try Sync.makeClient(store: store, urlString: "ws://127.0.0.1:9999",
2
credentials: SyncCredentials.makeNone())
3
try client.start()
Copied!
1
SyncClient syncClient = Sync.client(
2
store,
3
'ws://127.0.0.1:9999', // wss for SSL, ws for unencrypted traffic
4
SyncCredentials.none());
5
syncClient.start(); // connect and start syncing
Copied!
1
std::shared_ptr<obx::SyncClient> syncClient = obx::Sync::client(
2
store,
3
"ws://127.0.0.1:9999", // wss for SSL, ws for unencrypted traffic
4
obx::SyncCredentials::none()
5
);
6
syncClient->start(); // connect and start syncing
Copied!
1
OBX_sync* sync_client = obx_sync(store, "ws://127.0.0.1:9999"); // wss for SSL
2
obx_sync_credentials(sync_client, OBXSyncCredentialsType_NONE, NULL, 0);
3
obx_sync_start(sync_client); // connect and start syncing
Copied!
1
syncClient, err := objectbox.NewSyncClient(
2
store,
3
"ws://127.0.0.1", // wss for SSL, ws for unencrypted traffic
4
objectbox.SyncCredentialsNone())
5
6
if err != nil {
7
err = syncClient.Start() // Connect and start syncing.
8
}
Copied!
The example uses wss://127.0.0.1 for the server endpoint. This is the IP address of localhost and assumes that you run the server and client(s) on the same machine. If it's separate machines, you need to exhange 127.0.0.1 with an reachable IP address of the server, or, some valid DNS name.
Using Android emulator? You can use 10.0.2.2 to reach the host (the machine running the emulator). Details
Sync client is started by calling start()/buildAndStart(). It will then try to connect to the server, authenticate and start syncing. Read below for more configuration options you can use before starting the connection.
Once the client is logged in, the server will push any changes it has missed. The server will also push any future changes while the client remains connected. This sync updates behavior can be configured.
All of this happens asynchronously. To observe these events (log in, sync completed, …) read below on how to configure an event listener.
The client will now also push changes to the server for each Store transaction.
Note: For various reasons, ensure to limit transaction size to around 120 KB (e.g. watch out for BLOB data like pictures). With compression, this limit may be higher depending on your data.
If you cannot avoid large transaction sizes, please reach out to us.
Should the client get disconnected, e.g. due to internet connection issues, it will automatically try to reconnect using an exponential backoff. Once the connection suceeds, data synchronization resumes.

Drop-off, send-only clients

For some use cases, client should only report data and thus only send updates without ever receiving any data. We call those "drop-off clients". Technically, from an API perspective, these clients do not request updates from the server. Because requesting updates is the default, the sync client API has to be configured to do "manual" updates to actually disable updates from the server. This configuration has to happen before the client starts.
1
// C++; create syncClient as above, but do not start() just yet
2
syncClient->setRequestUpdatesMode(OBXRequestUpdatesMode_MANUAL);
3
syncClient->start();
Copied!

Secure Connection

When using wss as the protocol in the server URL a TLS encrypted connection is established. Use ws instead to turn off transport encryption (insecure, not recommended! e.g. only use for testing).

Authentication options

These are the currently supported options for authentication with a sync server:

Shared secret

Java
Kotlin
Swift
Dart/Flutter
C++
C
Go
1
SyncCredentials credentials = SyncCredentials.sharedSecret("<secret>");
Copied!
1
val credentials = SyncCredentials.sharedSecret("<secret>")
Copied!
Coming soon!
1
// use a string
2
SyncCredentials credentials = SyncCredentials.sharedSecretString("<secret>");
3
4
// or a byte vector
5
Uint8List secret = Uint8List.fromList([0, 46, 79, 193, 185, 65, 73, 239, 15, 5]);
6
SyncCredentials credentials = SyncCredentials.sharedSecretUint8List(secret);
Copied!
1
// use a string
2
obx::SyncCredentials creds = obx::SyncCredentials::sharedSecret("string");
3
4
// or a byte vector
5
std::vector<uint8_t> secret = {0, 46, 79, 193, 185, 65, 73, 239, 15, 5, 189, 186};
6
obx::SyncCredentials creds = obx::SyncCredentials::sharedSecret(std::move(secret));
Copied!
1
// use a string
2
const char* secret = "secret"
3
obx_sync_credentials(sync_client,
4
OBXSyncCredentialsType_SHARED_SECRET,
5
secret,
6
strlen(secret)
7
);
8
9
// or a byte vector
10
uint8_t secret[] = {0, 46, 79, 193, 185, 65, 73, 239, 15, 5, 189, 186};
11
obx_sync_credentials(sync_client,
12
OBXSyncCredentialsType_SHARED_SECRET,
13
secret,
14
sizeof(secret)
15
);
Copied!
1
// use a string
2
var creds = objectbox.SyncCredentialsSharedSecret([]byte("string"))
3
4
// or a byte vector
5
var secret = []byte{0, 46, 79, 193, 185, 65, 73, 239, 15, 5, 189, 186}
6
var creds = objectbox.SyncCredentialsSharedSecret(secret)
Copied!
This can be any pre-shared secret string or a byte sequence.

Google Sign-In

Java
Kotlin
Swift
Dart/Flutter
C++
C
Go
1
SyncCredentials credentials = SyncCredentials.google(account.getIdToken());
Copied!
1
val credentials = SyncCredentials.google(account.getIdToken())
Copied!
Coming soon!
1
// use a string
2
SyncCredentials credentials = SyncCredentials.googleAuthString("<secret>");
3
4
// or a byte vector
5
Uint8List secret = Uint8List.fromList([0, 46, 79, 193, 185, 65, 73, 239, 15, 5]);
6
SyncCredentials credentials = SyncCredentials.googleAuthUint8List(secret);
Copied!
Coming soon!
1
obx_sync_credentials(sync_client,
2
OBXSyncCredentialsType_GOOGLE_AUTH,
3
googleIdToken,
4
strlen(googleIdToken)
5
);
Copied!
1
// use a string
2
var creds = objectbox.SyncCredentialsGoogleAuth([]byte("string"))
3
4
// or a byte vector
5
var secret = []byte{0, 46, 79, 193, 185, 65, 73, 239, 15, 5, 189, 186}
6
var creds = objectbox.SyncCredentialsGoogleAuth(secret)
Copied!
The ObjectBox sync server supports authenticating users using their Google account. This assumes Google Sign-In is integrated into the app and it has obtained the user's ID token.

No authentication (insecure)

Never use this option in an app shipped to customers. It is inherently insecure and allows anyone to connect to the sync server.
Java
Kotlin
Swift
Dart/Flutter
C++
C
Go
1
SyncCredentials credentials = SyncCredentials.none();
Copied!
1
val credentials = SyncCredentials.none()
Copied!
Coming soon!
1
SyncCredentials credentials = SyncCredentials.none();
Copied!
1
obx::SyncCredentials credentials = obx::SyncCredentials::none();
Copied!
1
obx_sync_credentials(sync_client, OBXSyncCredentialsType_NONE, NULL, 0)
Copied!
1
var creds = objectbox.SyncCredentialsNone()
Copied!
For development and testing, it is often easier to just have no authentication at all to quickly get things up and running.

Manually start

Using the example above, the sync client automatically connects to the server and starts to sync. It is also possible to just build the client and then start to sync once your code is ready to.
Java
Kotlin
1
// Just build the client.
2
SyncClient syncClient = Sync.client(...).build();
3
4
// Start now.
5
syncClient.start();
Copied!
1
// Just build the client.
2
val syncClient = Sync.client(...).build()
3
4
// Start now.
5
syncClient.start()
Copied!
Note that a started sync client can not be started again. Stop and close an existing one and build a new one instead.

Listening to events

The sync client supports listening to various events, e.g. if authentication has failed or if the client was disconnected from the server. This enables other components of an app, like the user interface, to react accordingly.
Java
Kotlin
Swift
Dart/Flutter
C++
C
Go
It's possible to set one or more specific listeners that observe some events, or a general listener that observes all events. When building a Sync client use:
  • loginListener(listener) to observe login events.
  • completedListener(listener) to observe when synchronization has completed.
  • connectionListener(listener) to observe connection events.
  • listener(listener) to observe all of the above events. Use AbstractSyncListener and only override methods of interest to simplify your listener implementation.
See the description of each listener class and its methods for details.
Note that listeners can also be set or removed at any later point using SyncClient.setSyncListener(listener) and related methods.
1
SyncLoginListener loginListener = new SyncLoginListener() {
2
@Override
3
public void onLoggedIn() {
4
// Login succesful.
5
}
6
7
@Override
8
public void onLoginFailed(long syncLoginCode) {
9
// Login failed. Returns one of SyncLoginCodes.
10
}
11
};
12
13
SyncCompletedListener completedListener = new SyncCompletedListener() {
14
@Override
15
public void onUpdatesCompleted() {
16
// A sync has completed, client is up-to-date.
17
}
18
};
19
20
SyncConnectionListener connectListener = new SyncConnectionListener() {
21
@Override
22
public void onDisconnected() {
23
// Client disconnected from the server.
24
// Depending on the configuration it will try to re-connect.
25
}
26
};
27
28
// Set listeners when building the client.
29
SyncClient syncClient = Sync.client(...)
30
.loginListener(loginListener)
31
.completedListener(completedListener)
32
.connectionListener(connectListener)
33
.build();
34
35
// Set (or replace) a listener later.
36
syncClient.setSyncLoginListener(listener);
37
38
// Remove an existing listener.
39
syncClient.setSyncConnectionListener(null);
Copied!
It's possible to set one or more specific listeners that observe some events, or a general listener that observes all events. When building a Sync client use:
  • loginListener(listener) to observe login events.
  • completedListener(listener) to observe when synchronization has completed.
  • connectionListener(listener) to observe connection events.
  • listener(listener) to observe all of the above events. Use AbstractSyncListener and only override methods of interest to simplify your listener implementation.
See the description of each listener class and its methods for details.
Note that listeners can also be set or removed at any later point using SyncClient.setSyncListener(listener) and related methods.
1
val loginListener: SyncLoginListener = object : SyncLoginListener {
2
override fun onLoggedIn() {
3
// Login succesful.
4
}
5
6
override fun onLoginFailed(syncLoginCode: Long) {
7
// Login failed. Returns one of SyncLoginCodes.
8
}
9
}
10
11
val completedListener = SyncCompletedListener {
12
// A sync has completed, client is up-to-date.
13
}
14
15
val connectListener = object : SyncConnectionListener {
16
override fun onDisconnected() {
17
// Client disconnected from the server.
18
// Depending on the configuration it will try to re-connect.
19
}
20
}
21
22
// Set listeners when building the client.
23
val syncClient = Sync.client(...)
24
.loginListener(loginListener)
25
.completedListener(completedListener)
26
.connectionListener(connectListener)
27
.build()
28
29
// Set (or replace) a listener later.
30
syncClient.setSyncLoginListener(listener)
31
32
// Remove an existing listener.
33
syncClient.setSyncConnectionListener(null)
Copied!
It's possible to set one or more specific listeners that observe some events, or a general listener that observes all events. The SyncClient protocol offers the following properties to attach listeners:
  • loginListener to observe login events.
  • completedListener to observe when synchronization has completed.
  • connectionListener to observe connection events.
  • listener to observe all of the above events.
There is a protocol for each listener type. Note that listeners can also be set or removed at any later point by setting the listener property to nil.
By implementing a listener protocol and setting the matching property in SyncClient, you are called back. Let's have a look at the available listener protocols for details:
1
/// Listens to login events.
2
public protocol SyncLoginListener {
3
/// Called on a successful login.
4
///
5
/// At this point the connection to the sync destination was established and
6
/// entered an operational state, in which data can be sent both ways.
7
func loggedIn()
8
9
/// Called on a login failure with a `result` code specifying the issue.
10
func loginFailed(result: SyncCode)
11
}
12
13
/// Listens to sync completed events.
14
public protocol SyncCompletedListener {
15
/// Called each time a sync was "completed", in the sense that the client
16
/// caught up with the current server state. The client is "up-to-date".
17
func updatesCompleted()
18
}
19
20
/// Listens to sync connection events.
21
public protocol SyncConnectionListener {
22
/// Called when connection is established; happens before an actual login
23
func connected()
24
25
/// Called when the client is disconnected from the sync server, e.g. due to a network error.
26
///
27
/// Depending on the configuration, the sync client typically tries to reconnect automatically,
28
/// triggering a `SyncLoginListener` again.
29
func disconnected()
30
}
31
32
/// Listens to all possible sync events. See each protocol for detailed information.
33
public protocol SyncListener: SyncLoginListener, SyncCompletedListener, SyncChangeListener, SyncConnectionListener {
34
35
}
Copied!
It's possible to listen to sync-related events on the client. Use the following SyncClient getters to connect to a stream:
  • Stream<SyncLoginEvent> get loginEvents - such as logged-in, credentials-rejected.
  • Stream<void> get completionEvents to observe when synchronization has completed.
  • Stream<SyncConnectionEvent> get connectionEvents to observe connection events.
Note that these streams don't buffer events so unless you're subscribed, no events are collected. Additionally, don't forget to cancel the subscription when you don't care about the information anymore, to free up resources.
1
final client = Sync.client(...);
2
final subscription = client.loginEvents.listen((SycnLoginEvent event) {
3
if (event == SyncLoginEvent.loggedIn) print('Logged in successfully');
4
});
5
6
client.start();
7
8
...
9
10
// don't forget unsubscribe if you don't care about the events anymore
11
subscription.cancel();
Copied!
1
struct LoginListener : public obx::SyncClientLoginListener {
2
void loggedIn() noexcept override;
3
void loginFailed(OBXSyncCode code) noexcept override;
4
};
5
6
auto loginListener = std::make_shared<LoginListener>();
7
syncClient->setLoginListener(loginListener);
8
9
// there can be only one listener of a given type, so calling again with a
10
// different callback changes the listener (un-assigns the previous one)
11
syncClient->setLoginListener(...);
12
13
// reset (remove) a listener
14
syncClient->setLoginListener(nullptr);
Copied!
1
void login_listener(void* arg) {
2
(*(int*) arg)++;
3
}
4
5
void main() {
6
...
7
int login_listener_arg = 0;
8
obx_sync_listener_login(sync_client, login_listener, &login_listener_arg);
9
}
10
11
// there can be only one listener of a given type, so calling again with a
12
// different callback changes the listener (un-assigns the previous one)
13
obx_sync_listener_login(sync_client, ..., ...);
14
15
// reset (remove) a listener
16
obx_sync_listener_login(sync_client, NULL, NULL);
Copied!
1
syncClient.SetLoginListener(func() { println("Logged-in") })
2
3
// there can be only one listener of a given type, so calling again with a
4
// different callback changes the listener (un-assigns the previous one)
5
syncClient.SetLoginListener(func() { ... })
6
7
// reset (remove) a listener
8
syncClient.SetLoginListener(nil)
Copied!

Advanced

Listening to incoming data changes

For advanced use cases, it might be useful to know exactly which objects have changed during an incoming sync update. This is typically not necessary, as observing a box or a query may be easier.
On each sync update received on the client, the listener is called with an array of "Sync Change" objects, one for each affected entity type. It includes a list of affected object IDs - the ones that were put or removed in the incoming update.
Java
Kotlin
Swift
Dart/Flutter
C++
C
Go
Use changeListener(changeListener) when building the client and pass a SyncChangeListener to receive detailed information for each sync update. Or set or remove it at any later point using SyncClient.setSyncChangeListener(changeListener).
1
SyncChangeListener changeListener = syncChanges -> {
2
for (SyncChange syncChange : syncChanges) {
3
// This is equal to Example_.__ENTITY_ID.
4
long entityId = syncChange.getEntityTypeId();
5
// The @Id values of changed and removed entities.
6
long[] changed = syncChange.getChangedIds();
7
long[] removed = syncChange.getRemovedIds();
8
}
9
};
10
// Set the listener when building the client.
11
syncBuilder.changeListener(changeListener);
12
// Or set the listener later.
13
syncClient.setSyncChangeListener(changeListener);
14
15
// Calling again replaces an existing listener.
16
syncClient.setSyncChangeListener(changeListener);
17
// Remove an existing listener.
18
syncClient.setSyncChangeListener(null);
Copied!
Use changeListener(changeListener) when building the client and pass a SyncChangeListener to receive detailed information for each sync update. Or set or remove it at any later point using SyncClient.setSyncChangeListener(changeListener).
1
val changeListener = SyncChangeListener { syncChanges ->
2
for (syncChange in syncChanges) {
3
// This is equal to Example_.__ENTITY_ID.
4
val entityId = syncChange.entityTypeId
5
// The @Id values of changed and removed entities.
6
val changed = syncChange.changedIds
7
val removed = syncChange.removedIds
8
}
9
}
10
// Set the listener when building the client.
11
syncBuilder.changeListener(changeListener)
12
// Or set the listener later.
13
syncClient.setSyncChangeListener(changeListener)
14
15
// Calling again replaces an existing listener.
16
syncClient.setSyncChangeListener(changeListener)
17
// Remove an existing listener.
18
syncClient.setSyncChangeListener(null)
Copied!
Coming soon!
Use Stream<List<SyncChange>> get changeEvents on the SyncClient to receive detailed information for each sync update. Make sure to cancel the subscription when you don't need the information anymore to clear up resources.
1
final subscription = client.changeEvents
2
.listen((List<SyncChange> event) => event.forEach((change) {
3
print('${change.entity}(${change.entityId}) '
4
'puts=${change.puts} removals=${change.removals}');
5
}));
6
7
...
8
9
// don't forget unsubscribe if you don't care about the events anymore
10
subscription.cancel();
Copied!
1
/// Sample listener collecting all puts and removals
2
class StatsCollector {
3
struct EntityChanges {
4
std::vector<obx_id> puts;
5
std::vector<obx_id> removals;
6
};
7
std::unordered_map<obx_schema_id, EntityChanges> statsPerEntity;
8
9
/// Receives changes on the object instance, forwarded by the static forward().
10
void onChanges(const OBX_sync_change_array* changes) {
11
for (size_t i = 0; i < changes->count; i++) {
12
const OBX_sync_change& change = changes->list[i];
13
EntityChanges& stats = statsPerEntity[change.entity_id];
14
if (change.puts) collect(change.puts, stats.puts);
15
if (change.removals) collect(change.puts, stats.removals);
16
}
17
}
18
19
/// Update given vector by adding all ids from current change list.
20
void collect(const OBX_id_array* ids, std::vector<obx_id>& targetVector) {
21
targetVector.reserve(targetVector.size() + ids->count);
22
for (size_t i = 0; i < ids->count; i++) {
23
targetVector.push_back(ids->ids[i]);
24
}
25
}
26
27
public:
28
/// Just forwards the C-callback to the instance of this class.
29
static void forward(void* arg, const OBX_sync_change_array* changes) {
30
static_cast<StatsCollector*>(arg)->onChanges(changes);
31
}
32
};
33
34
35
void main() {
36
...
37
StatsCollector collector;
38
syncClient->setChangeListener(StatsCollector::forward, &collector);
39
}
Copied!
1
void on_puts(void* arg, obx_schema_id entity_id, const OBX_id_array* ids) {
2
//...
3
}
4
5
void on_removals(void* arg, obx_schema_id entity_id, const OBX_id_array* ids) {
6
//...
7
}
8
9
void change_listener(void* arg, const OBX_sync_change_array* changes) {
10
for (size_t i = 0; i < changes->count; i++) {
11
const OBX_sync_change* change = &changes->list[i];
12
if (change->puts) {
13
on_puts(arg, change->entity_id, change->puts);
14
}
15
if (change->removals) {
16
on_removals(arg, change->entity_id, change->removals);
17
}
18
}
19
};
20
21
void main() {
22
...
23
obx_sync_listener_login(sync_client, change_listener, &change_listener_arg);
24
}
Copied!
1
syncClient.SetChangeListener(func(changes []*objectbox.SyncChange) {
2
fmt.Printf("received %d changes\n", len(changes))
3
for i, change := range changes {
4
fmt.Printf("change %d: %v\n", i, change)
5
6
// change.EntityId is a "model-entity-id", e.g. we can choose to process
7
// only changes on Entity `User`, with the generated `UserBinding`:
8
if change.EntityId == model.UserBinding.Id {
9
fmt.Printf("put user IDs %v\n", change.Puts)
10
fmt.Printf("deleted user IDs %v\n", change.Removals)
11
}
12
}
13
})
Copied!

Listeners concurrency

Some events may be issued in parallel, from multiple background threads. To help you understand when and how you need to take care of concurrency (e.g. use mutex/atomic variables), we've grouped the sync listeners to these two groups:
There can be only one event executed at any single moment from a listener in a single group. You can imagine this as if there were two parallel threads, one could only issue "state" events, the other only "data change" events.

Controlling sync updates behavior

By default, after the Sync client is logged in, its database is updated from the server and the client will automatically subscribe for any future changes. For advanced use cases, like unit testing, it is possible to control when the client receives data updates from the server.
To change the default behavior, configure the "Request Updates Mode" before starting the client connection. Three modes are available:
  • automatic (default): receives updates on login and subscribes for future updates.
  • automatic, but no pushes: receives updates on login but doesn't subscribe for future updates.
  • manual: no automatic updates on login or on any updates in the future.
When using one of the non-default modes, synchronization can be controlled after login during application runtime by requesting and cancelling updates using the client:
Java
Kotlin
Swift
Dart/Flutter
C++
C
Go
1
SyncClient syncClient = syncBuilder
2
// Turn off automatic sync updates.
3
.requestUpdatesMode(RequestUpdatesMode.MANUAL)
4
.build();
5
6
// Wait for login attempt, proceed if logged in.
7
syncClient.awaitFirstLogin(20 * 1000 /* ms */);
8
if (syncClient.isLoggedIn()) {
9
// Turn on automatic sync updates.
10
syncClient.requestUpdates();
11
12
// Turn off automatic sync updates, cancel ongoing sync.
13
syncClient.cancelUpdates();
14
15
// Request one-time update.
16
// Will update client with latest data.
17
syncClient.requestUpdatesOnce();
18
}
Copied!
1
val syncClient = syncBuilder
2
// Turn off automatic sync updates.
3
.requestUpdatesMode(RequestUpdatesMode.MANUAL)
4
.build()
5
6
// Wait for login attempt, proceed if logged in.
7
syncClient.awaitFirstLogin(20 * 1000 /* ms */)
8
if (syncClient.isLoggedIn()) {
9
// Turn on automatic sync updates.
10
syncClient.requestUpdates()
11
12
// Turn off automatic sync updates, cancel ongoing sync.
13
syncClient.cancelUpdates()
14
15
// Request one-time update.
16
// Will update client with latest data.
17
syncClient.requestUpdatesOnce()
18
}
Copied!
Coming soon!
1
final client = Sync.client(...);
2
3
client.setRequestUpdatesMode(SyncRequestUpdatesMode.manual);
4
client.start(); // Connect but don't synchronize yet.
5
6
// Turn on sync updates and subscribe for pushes.
7
client.requestUpdates(subscribeForFuturePushes: true);
8
9
// Cancel ongoing synchronization & unsubscribe from future updates.
10
client.cancelUpdates();
11
12
// Alternatively, catch up with the server but don't subscribe for future.
13
// You can call this instead of subscribing to do one-time updates as needed.
14
client.requestUpdates(subscribeForFuturePushes: false);
Copied!
1
std::shared_ptr<obx::SyncClient> syncClient = obx::Sync::client(store, ...);
2
3
syncClient->setRequestUpdatesMode(OBXRequestUpdatesMode_MANUAL);
4
syncClient->start(); // Connect but don't synchronize yet.
5
6
// Turn on sync updates and subscribe for pushes.
7
syncClient->requestUpdates(true);
8
9
// Cancel ongoing synchronization & unsubscribe from future updates.
10
syncClient->cancelUpdates();
11
12
// Alternatively, catch up with the server but don't subscribe for future.
13
// You can call this instead of subscribing to do one-time updates as needed.
14
syncClient->requestUpdates(false);
Copied!
1
OBX_sync* sync_client = obx_sync(store, ...);
2
obx_sync_credentials(sync_client, ...);
3
4
obx_sync_request_updates_mode(sync_client, OBXRequestUpdatesMode_MANUAL);
5
obx_sync_start(sync_client); // Connect but don't synchronize yet.
6
7
// Turn on sync updates and subscribe for pushes.
8
obx_sync_updates_request(sync_client, true);
9
10
// Cancel ongoing synchronization & unsubscribe from future updates.
11
obx_sync_updates_cancel(sync_client);
12
13
// Alternatively, catch up with the server but don't subscribe for future.
14
// You can call this instead of subscribing to do one-time updates as needed.
15
obx_sync_updates_request(sync_client, false);
Copied!
1
syncClient, err := objectbox.NewSyncClient(...)
2
3
syncClient.SetRequestUpdatesMode(objectbox.SyncRequestUpdatesManual)
4
syncClient.Start() // Connect but don't synchronize yet.
5
6
// Turn on sync updates and subscribe for pushes.
7
syncClient.RequestUpdates(true)
8
9
// Cancel ongoing synchronization & unsubscribe from future updates.
10
syncClient.CancelUpdates()
11
12
// Alternatively, catch up with the server but don't subscribe for future.
13
// You can call this instead of subscribing to do one-time updates as needed.
14
syncClient->requestUpdates(false)
Copied!
Last modified 9d ago