Created
May 3, 2016 15:10
-
-
Save cmelchior/8786ec511f7e1f47673935a26f568106 to your computer and use it in GitHub Desktop.
Example of using Realm.waitForChange()/Realm.stopWaitForChange()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@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?