Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example of using Realm.waitForChange()/Realm.stopWaitForChange()
// Create a background thread
RealmThread t = new RealmThread(realmConfig, new RealmRunnable() {
@Override
public void run(Realm realm) {
do {
// Do some work once, and every time the Realm changes
} while (realm.waitForChange())
}
});
t.start(); // Start the thread
t.shutdown(); // Quit the loop as soon as possible.
public final class RealmThread extends Thread {
private final RealmConfiguration realmConfig;
private final RealmRunnable task;
private Realm realm;
public RealmThread(RealmConfiguration realmConfig, RealmRunnable task) {
super();
this.realmConfig = realmConfig;
this.task = task;
}
public RealmThread(RealmConfiguration realmConfig, RealmRunnable task, String threadName) {
super(threadName);
this.realmConfig = realmConfig;
this.task = task;
}
@Override
public void run() {
realm = Realm.getInstance(realmConfig);
if (task != null) {
task.run(realm);
}
synchronized(this) {
if (!realm.isClosed()) {
realm.close();
}
realm = null;
}
}
/**
* Abort the Realm thread as soon as possibly.
*/
public void shutdown() {
synchronized (this) {
if (!isAlive() || realm == null) {
return;
}
realm.stopWaitForChange();
}
}
// Runnable interface
public interface RealmRunnable {
void run(final Realm realm);
}
}
@ZherebtsovAlexandr

This comment has been minimized.

Copy link

commented Oct 19, 2016

@cmelchior please explain why we should quit the loop as soon as possible? Can I execute shutdown when I need unsubscribe from Realm changes notifications?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.