Skip to content

Instantly share code, notes, and snippets.

@IlyaGulya
Created December 13, 2016 14:42
Show Gist options
  • Save IlyaGulya/a72caf3f8b9ab859306327fd014ea212 to your computer and use it in GitHub Desktop.
Save IlyaGulya/a72caf3f8b9ab859306327fd014ea212 to your computer and use it in GitHub Desktop.
Simple utils for Realm.io database
package in.ccrowd.base.database;
import com.annimon.stream.Collectors;
import com.annimon.stream.Stream;
import io.realm.Realm;
import io.realm.RealmModel;
import io.realm.RealmObject;
import rx.functions.Func0;
public class RealmUtil {
public static void handleTransaction(final RunnableWithRealm toExecute) {
final Realm realm = Realm.getDefaultInstance();
boolean alreadyInTransaction = realm.isInTransaction();
if (!alreadyInTransaction) {
realm.beginTransaction();
}
toExecute.execute(realm);
if (!alreadyInTransaction) {
realm.commitTransaction();
}
}
public static void handleTransaction(final Runnable toExecute) {
handleTransaction(realm -> toExecute.run());
}
public static <T> T handleTransactionForResult(final Returnable<T> toExecute) {
return handleTransactionForResult(realm -> toExecute.getValue());
}
public static <T> T handleTransactionForResult(final ReturnableWithRealm<T> toExecute) {
final Realm realm = Realm.getDefaultInstance();
boolean alreadyInTransaction = realm.isInTransaction();
if (!alreadyInTransaction) {
realm.beginTransaction();
}
T value = toExecute.getValue(realm);
if (!alreadyInTransaction) {
realm.commitTransaction();
}
return value;
}
public static <T extends WithId> T newInstance(final Class<T> clazz, final Func0<T> generator) {
return newInstance(() -> {
final T object = generator.call();
object.setId(PrimaryKeyFactory.getNextId(clazz));
return object;
});
}
public static <T extends WithId> T newInstance(final Func0<T> generator) {
return RealmUtil.handleTransactionForResult(() -> {
final T object = generator.call();
return Realm.getDefaultInstance()
.copyToRealmOrUpdate(object);
});
}
public static <T extends RealmObject> T getById(final Class<T> clazz, final long id) {
return Realm.getDefaultInstance()
.where(clazz)
.equalTo(Column.ID, id)
.findFirst();
}
public static String getField(final String... fields) {
return Stream.of(fields)
.collect(Collectors.joining("."));
}
public interface RunnableWithRealm {
void execute(Realm realm);
}
public interface Returnable<T> {
T getValue();
}
public interface ReturnableWithRealm<T> {
T getValue(Realm realm);
}
public interface WithId extends RealmModel {
int getId();
void setId(int id);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment