Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@cmelchior
Created May 3, 2016 15:10
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cmelchior/8786ec511f7e1f47673935a26f568106 to your computer and use it in GitHub Desktop.
Save cmelchior/8786ec511f7e1f47673935a26f568106 to your computer and use it in GitHub Desktop.
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
Copy link

ZherebtsovAlexandr 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