Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Example of using Realm.waitForChange()/Realm.stopWaitForChange()
// Create a background thread
RealmThread t = new RealmThread(realmConfig, new RealmRunnable() {
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) {
this.realmConfig = realmConfig;
this.task = task;
public RealmThread(RealmConfiguration realmConfig, RealmRunnable task, String threadName) {
this.realmConfig = realmConfig;
this.task = task;
public void run() {
realm = Realm.getInstance(realmConfig);
if (task != null) {;
synchronized(this) {
if (!realm.isClosed()) {
realm = null;
* Abort the Realm thread as soon as possibly.
public void shutdown() {
synchronized (this) {
if (!isAlive() || realm == null) {
// Runnable interface
public interface RealmRunnable {
void run(final Realm realm);

This comment has been minimized.

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
You can’t perform that action at this time.