Last active
September 22, 2017 19:20
-
-
Save Zhuinden/320b14d4e96f8aa5d45eb851552d3b8c to your computer and use it in GitHub Desktop.
Thread-local Realm
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
@Singleton | |
public class RealmManager { | |
private ThreadLocal<Realm> realms; | |
@Inject | |
public RealmManager() { | |
realms = new ThreadLocal<>(); | |
} | |
public Realm openRealm() { | |
Realm realm = realms.get(); | |
if(realm != null && !realm.isClosed()) { | |
throw new IllegalStateException("Realm is already open"); | |
} | |
realm = Realm.getDefaultInstance(); | |
realms.set(realm); | |
return realm; | |
} | |
public Realm getRealm() { | |
Realm realm = realms.get(); | |
if(realm == null) { | |
throw new IllegalStateException("There is no open Realm on this thread"); | |
} | |
return realm; | |
} | |
public void closeRealm() { | |
Realm realm = realms.get(); | |
if(realm == null) { | |
throw new IllegalStateException("No Realm found to close"); | |
} | |
if(!realm.isClosed()) { | |
realm.close(); | |
} | |
realms.set(null); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment