From my understanding, Realm can/should only be accessed from the main thread.
This is a misconception. While Realm auto-updates only on looper threads (such as the main thread), this does not mean you cannot create a new Realm instance on any thread.
If you want to open a Realm on your background thread, you could easily do this:
new Thread(new Runnable() {
@Override
public void run() {
Realm firstRealm = null;
Realm secondRealm = null;
try {
firstRealm = Realm.getInstance(firstConfiguration);
secondRealm = Realm.getInstance(secondConfiguration);
firstRealm.beginTransaction();
secondRealm.beginTransaction();
RealmResults<SomeObject> someObjects = firstRealm.where(SomeObject.class)
.equalTo(SomeObjectFields.VALID, true)
.findAll();
secondRealm.copyToRealmOrUpdate(someObjects); // I am not sure if you have to detach it first.
someObjects.deleteAllFromRealm();
secondRealm.commitTransaction();
firstRealm.commitTransaction();
} catch(Throwable e) {
if(firstRealm != null && firstRealm.isInTransaction()) {
firstRealm.cancelTransaction();
}
if(secondRealm != null && secondRealm.isInTransaction()) {
secondRealm.cancelTransaction();
}
throw e;
} finally {
if(firstRealm != null) {
firstRealm.close();
}
if(secondRealm != null) {
secondRealm.close();
}
}
}
}).start();
And to access the elements on the UI thread, you'd just need a UI thread Realm and a RealmResults
with a RealmChangeListener
bound to it.
public class MainActivity extends AppCompatActivity {
Realm realm;
@BindView(R.id.realm_recycler)
RecyclerView recyclerView;
RealmResults<SomeObject> listenerSet;
RealmChangeListener realmChangeListener = new RealmChangeListener() {
@Override
public void onChange(Object element) {
if(recyclerView != null && recyclerView.getAdapter() != null) {
recyclerView.getAdapter().notifyDataSetChanged();
}
}
});
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
realm = Realm.getDefaultInstance();
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
listenerSet = realm.where(SomeObject.class).findAll();
listenerSet.addChangeListener(realmChangeListener);
// set up recyclerView
adapter.updateData(realm.where(SomeObject.class).findAll());
}
@Override
public void onDestroy() {
super.onDestroy();
if(realm != null) {
realm.close();
realm = null;
}
}
}