We are starting to use Realm.io in the Android app project. But something that we don't like about the Realm.io API is the lack of an asynchronous way to query the database. In older projects, we used DbQuery and Sqlite, so we use to create database queries inside threads or AsyncTask . But itโs quite alarming to see that in all the examples, the queries are executed in UiThread . Isn't that bad for application performance ?. We tried to make requests inside threads or AsyncTasks, but we get an error when accessing model objects back in UiThread, stating that we cannot access RealObjects in threads that were not the ones where they were requested. Here is a sample code:
service.getDatabaseHelper() .with(getActivity()) //Context that I use to instance the Realm instance .onFinishQuery( new DatabaseHelper.IQueryGetCallback<UserRealm>() { @Override public void onGetResult(UserRealm[] results) { for(UserRealm aUser : results){ //Here is where it crashes Log.d("Log","Username -> "+aUser.getName()); } } }) .getUsersFromDb(); //....... //In our "DAO" class public void getUsersFromDb(){ new GetQueryTask() { @Override public UserRealm[] onQueryReadyToBeExecuted(Realm realmInstance) { RealmQuery<UserRealm> query = realmInstance.where(UserRealm.class); RealmResults<UserRealm> result = query.findAll(); // TODO hacer que devuelva un array ArrayList<UserRealm> users = new ArrayList<UserRealm>(); for (UserRealm u : result) { //Here we can read the RealObject fine users.add(u); } return users.toArray(new UserRealm[users.size()]); } }.execute(); } //Our abstract task that wraps all the instantiation-transaction behaviour public abstract class GetQueryTask<T extends RealmObject> extends AsyncTask<Void, Void, T[]> { @Override protected T[] doInBackground(Void... params) { //We tried to instantiate this class in several places, here //Send it as parameter through the AsyncTask //context is set in the with(Context ctx) method. Realm realm = Realm.getInstance(context); return onQueryReadyToBeExecuted(realm); } public abstract T[] onQueryReadyToBeExecuted(Realm realmInstance); @Override protected void onPostExecute(T[] result) { mCallback.onExecute(result); } }
Our main problem is not the โerrorโ of this code, but the fact that we make requests in UiThread, like the developers of Realm.io, in our examples. If so, then all this code will no longer be needed to execute asynchronous requests.
source share