/** * Creates a filterable {@link RealmProxyMediator}. * * @param originalMediator the original auto generated mediator. * @param allowedClasses the subset of classes from original mediator to allow. */ public FilterableMediator(RealmProxyMediator originalMediator, Collection<Class<? extends RealmModel>> allowedClasses) { this.originalMediator = originalMediator; Set<Class<? extends RealmModel>> tempAllowedClasses = new HashSet<>(); //noinspection ConstantConditions if (originalMediator != null) { Set<Class<? extends RealmModel>> originalClasses = originalMediator.getModelClasses(); for (Class<? extends RealmModel> clazz : allowedClasses) { if (originalClasses.contains(clazz)) { tempAllowedClasses.add(clazz); } } } this.allowedClasses = Collections.unmodifiableSet(tempAllowedClasses); }
/** * Returns the {@link ColumnInfo} for the passed class name. * * @param simpleClassName the simple name of the class for which to get the ColumnInfo. * @return the corresponding {@link ColumnInfo} object. * @throws io.realm.exceptions.RealmException if the class cannot be found in the schema. */ @Nonnull public ColumnInfo getColumnInfo(String simpleClassName) { ColumnInfo columnInfo = simpleClassNameToColumnInfoMap.get(simpleClassName); if (columnInfo == null) { Set<Class<? extends RealmModel>> modelClasses = mediator.getModelClasses(); for (Class<? extends RealmModel> modelClass : modelClasses) { if (mediator.getSimpleClassName(modelClass).equals(simpleClassName)) { columnInfo = getColumnInfo(modelClass); simpleClassNameToColumnInfoMap.put(simpleClassName, columnInfo); break; } } } if (columnInfo == null) { throw new RealmException( String.format(Locale.US, "'%s' doesn't exist in current schema.", simpleClassName)); } return columnInfo; }
@Override public void init() { RealmResults<TodoList> listResults = todoRepository.queryList(listId); list = listResults.get(0); view.initViews(list.getTitle()); bindData(); list.addChangeListener(new RealmChangeListener<RealmModel>() { @Override public void onChange(RealmModel element) { if (view != null) { bindData(); view.notifyDataChanged(list.getTitle()); } } }); }
@Override public void init(long taskId) { RealmResults<Task> taskResults = repository.queryTask(taskId); if (taskResults.size() > 0) { task = taskResults.get(0); } task.addChangeListener(new RealmChangeListener<RealmModel>() { @Override public void onChange(RealmModel element) { task.getId(); view.updateViews(task); } }); view.initViews(); view.updateViews(task); }
public static <T extends RealmModel & TreeItem & Insertable> void deleteAndInsert(Realm realm, final Class<T> clazz, final List<T> elements) { Collections.sort(elements, TreeItem.COMPARATOR); realm.executeTransaction(realm1 -> { final RealmResults<T> databaseItems = realm1.where(clazz).findAllSorted(TreeItem.ID, Sort.ASCENDING); final Iterator<T> databaseIterator = databaseItems.iterator(); for (T element : elements) { T currentDatabaseItem; // The lists are sorted by id, so if currentDatabaseItem.getId() < element.getId() we can remove it from the database while (databaseIterator.hasNext() && (currentDatabaseItem = databaseIterator.next()).getId() < element.getId()) { currentDatabaseItem.delete(realm1); } element.insert(realm1); } // Remove remaining items from the database while (databaseIterator.hasNext()) { databaseIterator.next().delete(realm1); } }); }
/** * 增加或更新 */ public static <E extends RealmModel> E createOrUpdate(final E realmModel) { sRealm = Realm.getDefaultInstance(); sRealm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm realm) { E person = sRealm.copyToRealmOrUpdate(realmModel); } }, new Realm.Transaction.OnSuccess() { @Override public void onSuccess() { // Transaction was a success. } }, new Realm.Transaction.OnError() { @Override public void onError(Throwable error) { // Transaction failed and was automatically canceled. } }); sRealm.close(); return null; }
@Override public <T extends RealmModel> RealmQuery<T> transform(RealmQuery<T> realmQuery, Condition condition) { // Checks. if (!condition.isValid()) throw new IllegalArgumentException("Condition isn't valid."); if (condition.getType() != Condition.Type.NORMAL) throw new IllegalArgumentException("Condition type is not NORMAL."); // Get data from Conditions. String field = condition.getField(); FieldType fieldType = condition.getFieldType(); Object[] args = condition.getArgs(); // Use different methods based on field type. if (FieldType.DATE == fieldType) return realmQuery.lessThan(field, (Date) args[0]); else if (FieldType.DOUBLE == fieldType) return realmQuery.lessThan(field, (Double) args[0]); else if (FieldType.FLOAT == fieldType) return realmQuery.lessThan(field, (Float) args[0]); else if (FieldType.INTEGER == fieldType) return realmQuery.lessThan(field, (Integer) args[0]); else if (FieldType.LONG == fieldType) return realmQuery.lessThan(field, (Long) args[0]); else throw new IllegalArgumentException(String.format("Illegal argument type \"%s\".", fieldType.getTypeName())); }
@Override public <T extends RealmModel> RealmQuery<T> transform(RealmQuery<T> realmQuery, Condition condition) { // Checks. if (!condition.isValid()) throw new IllegalArgumentException("Condition isn't valid."); if (condition.getType() != Condition.Type.NORMAL) throw new IllegalArgumentException("Condition type is not NORMAL."); // Get data from Conditions. String field = condition.getField(); FieldType fieldType = condition.getFieldType(); Object[] args = condition.getArgs(); // Use different methods based on field type. if (FieldType.STRING == fieldType) return realmQuery.contains(field, (String) args[0]); else throw new IllegalArgumentException(String.format("Illegal argument type \"%s\".", fieldType.getTypeName())); }
@Override public <T extends RealmModel> RealmQuery<T> transform(RealmQuery<T> realmQuery, Condition condition) { // Checks. if (!condition.isValid()) throw new IllegalArgumentException("Condition isn't valid."); if (condition.getType() != Condition.Type.NORMAL) throw new IllegalArgumentException("Condition type is not NORMAL."); // Get data from Conditions. String field = condition.getField(); FieldType fieldType = condition.getFieldType(); Object[] args = condition.getArgs(); // Use different methods based on field type. if (FieldType.DATE == fieldType) return realmQuery.lessThanOrEqualTo(field, (Date) args[0]); else if (FieldType.DOUBLE == fieldType) return realmQuery.lessThanOrEqualTo(field, (Double) args[0]); else if (FieldType.FLOAT == fieldType) return realmQuery.lessThanOrEqualTo(field, (Float) args[0]); else if (FieldType.INTEGER == fieldType) return realmQuery.lessThanOrEqualTo(field, (Integer) args[0]); else if (FieldType.LONG == fieldType) return realmQuery.lessThanOrEqualTo(field, (Long) args[0]); else throw new IllegalArgumentException(String.format("Illegal argument type \"%s\".", fieldType.getTypeName())); }
@Override public <T extends RealmModel> RealmQuery<T> transform(RealmQuery<T> realmQuery, Condition condition) { // Checks. if (!condition.isValid()) throw new IllegalArgumentException("Condition isn't valid."); if (condition.getType() != Condition.Type.NORMAL) throw new IllegalArgumentException("Condition type is not NORMAL."); // Get data from Conditions. String field = condition.getField(); FieldType fieldType = condition.getFieldType(); Object[] args = condition.getArgs(); if (FieldType.STRING == fieldType) return realmQuery.beginsWith(field, (String) args[0]); else throw new IllegalArgumentException(String.format("Illegal argument type \"%s\".", fieldType.getTypeName())); }
@Override public <T extends RealmModel> RealmQuery<T> transform(RealmQuery<T> realmQuery, Condition condition) { // Checks. if (!condition.isValid()) throw new IllegalArgumentException("Condition isn't valid."); if (condition.getType() != Condition.Type.NORMAL) throw new IllegalArgumentException("Condition type is not NORMAL."); // Get data from Conditions. String field = condition.getField(); FieldType fieldType = condition.getFieldType(); Object[] args = condition.getArgs(); // Use different methods based on field type. if (FieldType.DATE == fieldType) return realmQuery.between(field, (Date) args[0], (Date) args[1]); else if (FieldType.DOUBLE == fieldType) return realmQuery.between(field, (Double) args[0], (Double) args[1]); else if (FieldType.FLOAT == fieldType) return realmQuery.between(field, (Float) args[0], (Float) args[1]); else if (FieldType.INTEGER == fieldType) return realmQuery.between(field, (Integer) args[0], (Integer) args[1]); else if (FieldType.LONG == fieldType) return realmQuery.between(field, (Long) args[0], (Long) args[1]); else throw new IllegalArgumentException(String.format("Illegal argument type \"%s\".", fieldType.getTypeName())); }
@Override public <T extends RealmModel> RealmQuery<T> transform(RealmQuery<T> realmQuery, Condition condition) { // Checks. if (!condition.isValid()) throw new IllegalArgumentException("Condition isn't valid."); if (condition.getType() != Condition.Type.NORMAL) throw new IllegalArgumentException("Condition type is not NORMAL."); // Get data from Conditions. String field = condition.getField(); FieldType fieldType = condition.getFieldType(); Object[] args = condition.getArgs(); // Use different methods based on field type. if (FieldType.BOOLEAN == fieldType) return realmQuery.equalTo(field, (Boolean) args[0]); else if (FieldType.DATE == fieldType) return realmQuery.equalTo(field, (Date) args[0]); else if (FieldType.DOUBLE == fieldType) return realmQuery.equalTo(field, (Double) args[0]); else if (FieldType.FLOAT == fieldType) return realmQuery.equalTo(field, (Float) args[0]); else if (FieldType.INTEGER == fieldType) return realmQuery.equalTo(field, (Integer) args[0]); else if (FieldType.LONG == fieldType) return realmQuery.equalTo(field, (Long) args[0]); else if (FieldType.SHORT == fieldType) return realmQuery.equalTo(field, (Short) args[0]); else if (FieldType.STRING == fieldType) return realmQuery.equalTo(field, (String) args[0]); else throw new IllegalArgumentException(String.format("Illegal argument type \"%s\".", fieldType.getTypeName())); }
@Override public <T extends RealmModel> RealmQuery<T> transform(RealmQuery<T> realmQuery, Condition condition) { // Checks. if (!condition.isValid()) throw new IllegalArgumentException("Condition isn't valid."); if (condition.getType() != Condition.Type.NORMAL) throw new IllegalArgumentException("Condition type is not NORMAL."); // Get data from Conditions. String field = condition.getField(); FieldType fieldType = condition.getFieldType(); Object[] args = condition.getArgs(); if (FieldType.STRING == fieldType) return realmQuery.endsWith(field, (String) args[0]); else throw new IllegalArgumentException(String.format("Illegal argument type \"%s\".", fieldType.getTypeName())); }
@Override public <T extends RealmModel> RealmQuery<T> transform(RealmQuery<T> realmQuery, Condition condition) { // Checks. if (!condition.isValid()) throw new IllegalArgumentException("Condition isn't valid."); if (condition.getType() != Condition.Type.NORMAL) throw new IllegalArgumentException("Condition type is not NORMAL."); // Get data from Conditions. String field = condition.getField(); FieldType fieldType = condition.getFieldType(); Object[] args = condition.getArgs(); // Use different methods based on field type. if (FieldType.BOOLEAN == fieldType) return realmQuery.notEqualTo(field, (Boolean) args[0]); else if (FieldType.DATE == fieldType) return realmQuery.notEqualTo(field, (Date) args[0]); else if (FieldType.DOUBLE == fieldType) return realmQuery.notEqualTo(field, (Double) args[0]); else if (FieldType.FLOAT == fieldType) return realmQuery.notEqualTo(field, (Float) args[0]); else if (FieldType.INTEGER == fieldType) return realmQuery.notEqualTo(field, (Integer) args[0]); else if (FieldType.LONG == fieldType) return realmQuery.notEqualTo(field, (Long) args[0]); else if (FieldType.SHORT == fieldType) return realmQuery.notEqualTo(field, (Short) args[0]); else if (FieldType.STRING == fieldType) return realmQuery.notEqualTo(field, (String) args[0]); else throw new IllegalArgumentException(String.format("Illegal argument type \"%s\".", fieldType.getTypeName())); }
@Override public <T extends RealmModel> RealmQuery<T> transform(RealmQuery<T> realmQuery, Condition condition) { // Checks. if (!condition.isValid()) throw new IllegalArgumentException("Condition isn't valid."); if (condition.getType() != Condition.Type.NORMAL) throw new IllegalArgumentException("Condition type is not NORMAL."); // Get data from Conditions. String field = condition.getField(); FieldType fieldType = condition.getFieldType(); Object[] args = condition.getArgs(); // Use different methods based on field type. if (FieldType.DATE == fieldType) return realmQuery.greaterThan(field, (Date) args[0]); else if (FieldType.DOUBLE == fieldType) return realmQuery.greaterThan(field, (Double) args[0]); else if (FieldType.FLOAT == fieldType) return realmQuery.greaterThan(field, (Float) args[0]); else if (FieldType.INTEGER == fieldType) return realmQuery.greaterThan(field, (Integer) args[0]); else if (FieldType.LONG == fieldType) return realmQuery.greaterThan(field, (Long) args[0]); else throw new IllegalArgumentException(String.format("Illegal argument type \"%s\".", fieldType.getTypeName())); }
@Override public <T extends RealmModel> RealmQuery<T> transform(RealmQuery<T> realmQuery, Condition condition) { // Checks. if (!condition.isValid()) throw new IllegalArgumentException("Condition isn't valid."); if (condition.getType() != Condition.Type.NORMAL) throw new IllegalArgumentException("Condition type is not NORMAL."); // Get data from Conditions. String field = condition.getField(); FieldType fieldType = condition.getFieldType(); Object[] args = condition.getArgs(); // Use different methods based on field type. if (FieldType.DATE == fieldType) return realmQuery.greaterThanOrEqualTo(field, (Date) args[0]); else if (FieldType.DOUBLE == fieldType) return realmQuery.greaterThanOrEqualTo(field, (Double) args[0]); else if (FieldType.FLOAT == fieldType) return realmQuery.greaterThanOrEqualTo(field, (Float) args[0]); else if (FieldType.INTEGER == fieldType) return realmQuery.greaterThanOrEqualTo(field, (Integer) args[0]); else if (FieldType.LONG == fieldType) return realmQuery.greaterThanOrEqualTo(field, (Long) args[0]); else throw new IllegalArgumentException(String.format("Illegal argument type \"%s\".", fieldType.getTypeName())); }
/** * Query the database * * @param passedQuery The query to search with. If null is passed here, it will build a default * query in which it searches everything. * @param myClass Class (table) that is being searched * @param <T> T extends RealmModel (RealmResults) * @return An object from the database (one from that table) */ public <T extends RealmModel> Object queryDatabaseSingle(RealmQuery<T> passedQuery, Class myClass) { Realm realm = DatabaseUtilities.buildRealm(this.realmConfiguration); if (passedQuery == null) { passedQuery = this.buildRealmQuery(realm, myClass); } //Start transaction RealmResults<T> results = passedQuery.findAll(); if (results != null) { Object object = results.get(0); return object; } return null; }
/** * Query the database * * @param passedQuery The query to search with. If null is passed here, it will build a default * query in which it searches everything. * @param myClass Class (table) that is being searched * @param <T> T extends RealmModel (RealmResults) * @return An list of objects from the database (all in that table) */ public <T extends RealmModel> List<Object> queryDatabaseList(RealmQuery<T> passedQuery, Class myClass) { Realm realm = DatabaseUtilities.buildRealm(this.realmConfiguration); if (passedQuery == null) { passedQuery = this.buildRealmQuery(realm, myClass); } //Start transaction RealmResults<T> results = passedQuery.findAll(); List<Object> objects = new ArrayList<>(); //<T extends RealmModel> if (results != null) { for (T t : results) { Object object = (Object) t; if (object != null) { objects.add(object); } } } return objects; }
/** * Returns a set of the classes (that extends RealmModel) that make up the current table * with the realmConfiguration. If the realmconfig is null, it will build one. * @return */ public Set<Class<? extends RealmModel>> getDBTableTypes(){ try { if (this.realmConfiguration == null) { this.realmConfiguration = DatabaseUtilities .buildRealmConfig(context, null, null, null); } } catch (Exception e){ e.printStackTrace(); } if(realmConfiguration == null){ return null; } return realmConfiguration.getRealmObjectClasses(); }
/** * Puts and element into the DB. * * @param realmModel Element to insert in the DB. * @param dataClass Class type of the items to be put. */ @NonNull @Override // TODO: 6/13/17 Remove ? remove : create flow public <M extends RealmModel> Single<Boolean> put(@Nullable M realmModel, @NonNull Class dataClass) { return Single.fromCallable(() -> { if (realmModel == null) { throw new IllegalArgumentException("RealmObject is null"); } else { return getRealm(Realm.getDefaultInstance()).map(realm1 -> RealmObject.isValid(executeWriteOperationInRealm(realm1, () -> realm1.copyToRealmOrUpdate(realmModel)))) .blockingFirst(); } }); }
public static <T extends RealmModel> Flowable<RealmResults<T>> getRealmItems(Class clazz, HashMap<String, String> map) { return Flowable.create(new FlowableOnSubscribe<RealmResults<T>>() { @Override public void subscribe(FlowableEmitter<RealmResults<T>> emitter) throws Exception { Realm realm = Realm.getDefaultInstance(); RealmQuery<T> query = realm.where(clazz); if (map != null) { for (Map.Entry<String, String> entry : map.entrySet()) { query.equalTo(entry.getKey(), entry.getValue()); } } RealmResults<T> results = query.findAll(); final RealmChangeListener<RealmResults<T>> listener = _realm -> { if (!emitter.isCancelled()) { emitter.onNext(results); } }; emitter.setDisposable(Disposables.fromRunnable(() -> { results.removeChangeListener(listener); realm.close(); })); results.addChangeListener(listener); emitter.onNext(results); } }, BackpressureStrategy.LATEST); }
@Override public Map<Class<? extends RealmModel>, OsObjectSchemaInfo> getExpectedObjectSchemaInfoMap() { Map<Class<? extends RealmModel>, OsObjectSchemaInfo> infoMap = new HashMap<Class<? extends RealmModel>, OsObjectSchemaInfo>(); for (Map.Entry<Class<? extends RealmModel>, OsObjectSchemaInfo> entry : originalMediator.getExpectedObjectSchemaInfoMap().entrySet()) { if (allowedClasses.contains(entry.getKey())) { infoMap.put(entry.getKey(), entry.getValue()); } } return infoMap; }
@Override public <E extends RealmModel> E newInstance(Class<E> clazz, Object baseRealm, Row row, ColumnInfo columnInfo, boolean acceptDefaultValue, List<String> excludeFields) { checkSchemaHasClass(clazz); return originalMediator.newInstance(clazz, baseRealm, row, columnInfo, acceptDefaultValue, excludeFields); }
public CompositeMediator(RealmProxyMediator... mediators) { final HashMap<Class<? extends RealmModel>, RealmProxyMediator> tempMediators = new HashMap<>(); //noinspection ConstantConditions if (mediators != null) { for (RealmProxyMediator mediator : mediators) { for (Class<? extends RealmModel> realmClass : mediator.getModelClasses()) { tempMediators.put(realmClass, mediator); } } } this.mediators = Collections.unmodifiableMap(tempMediators); }
@Override public Map<Class<? extends RealmModel>, OsObjectSchemaInfo> getExpectedObjectSchemaInfoMap() { Map<Class<? extends RealmModel>, OsObjectSchemaInfo> infoMap = new HashMap<Class<? extends RealmModel>, OsObjectSchemaInfo>(); for (RealmProxyMediator mediator : mediators.values()) { infoMap.putAll(mediator.getExpectedObjectSchemaInfoMap()); } return infoMap; }
@Override public <E extends RealmModel> E newInstance(Class<E> clazz, Object baseRealm, Row row, ColumnInfo columnInfo, boolean acceptDefaultValue, List<String> excludeFields) { RealmProxyMediator mediator = getMediator(clazz); return mediator.newInstance(clazz, baseRealm, row, columnInfo, acceptDefaultValue, excludeFields); }
@Override public boolean transformerApplied() { for (Map.Entry<Class<? extends RealmModel>, RealmProxyMediator> entry : mediators.entrySet()) { if (!entry.getValue().transformerApplied()) { return false; } } return true; }
private RealmProxyMediator getMediator(Class<? extends RealmModel> clazz) { RealmProxyMediator mediator = mediators.get(clazz); if (mediator == null) { throw new IllegalArgumentException(clazz.getSimpleName() + " is not part of the schema for this Realm"); } return mediator; }
/** * Normalizes a input class to it's original RealmObject class so it is transparent whether or not the input class * was a RealmProxy class. */ public static Class<? extends RealmModel> getOriginalModelClass(Class<? extends RealmModel> clazz) { // This cast is correct because 'clazz' is either the type // generated by RealmProxy or the original type extending directly from RealmObject. @SuppressWarnings("unchecked") Class<? extends RealmModel> superclass = (Class<? extends RealmModel>) clazz.getSuperclass(); if (!superclass.equals(Object.class) && !superclass.equals(RealmObject.class)) { clazz = superclass; } return clazz; }
public <T extends RealmModel> void addListener(T observer, RealmObjectChangeListener<T> listener) { if (observerPairs.isEmpty()) { nativeStartListening(nativePtr); } ObjectObserverPair<T> pair = new ObjectObserverPair<T>(observer, listener); observerPairs.add(pair); }
/** * Returns the {@link ColumnInfo} for the passed class. * * @param clazz the class for which to get the ColumnInfo. * @return the corresponding {@link ColumnInfo} object. * @throws io.realm.exceptions.RealmException if the class cannot be found in the schema. */ @Nonnull public ColumnInfo getColumnInfo(Class<? extends RealmModel> clazz) { ColumnInfo columnInfo = classToColumnInfoMap.get(clazz); if (columnInfo == null) { columnInfo = mediator.createColumnInfo(clazz, osSchemaInfo); classToColumnInfoMap.put(clazz, columnInfo); } return columnInfo; }
/** * Refreshes all the existing {@link ColumnInfo} in the cache. */ public void refresh() { for (Map.Entry<Class<? extends RealmModel>, ColumnInfo> entry : classToColumnInfoMap.entrySet()) { ColumnInfo newColumnInfo = mediator.createColumnInfo(entry.getKey(), osSchemaInfo); entry.getValue().copyFrom(newColumnInfo); } }
@Override public String toString() { StringBuilder buf = new StringBuilder("ColumnIndices["); boolean commaNeeded = false; for (Map.Entry<Class<? extends RealmModel>, ColumnInfo> entry : classToColumnInfoMap.entrySet()) { if (commaNeeded) { buf.append(","); } buf.append(entry.getKey().getSimpleName()).append("->").append(entry.getValue()); commaNeeded = true; } return buf.append("]").toString(); }
@Override public <E extends RealmModel> Flowable<E> from(final Realm realm, final E object) { final RealmConfiguration realmConfig = realm.getConfiguration(); return Flowable.create(new FlowableOnSubscribe<E>() { @Override public void subscribe(final FlowableEmitter<E> emitter) throws Exception { // Gets instance to make sure that the Realm is open for as long as the // Observable is subscribed to it. final Realm observableRealm = Realm.getInstance(realmConfig); objectRefs.get().acquireReference(object); final RealmChangeListener<E> listener = new RealmChangeListener<E>() { @Override public void onChange(E obj) { if (!emitter.isCancelled()) { emitter.onNext(obj); } } }; RealmObject.addChangeListener(object, listener); // Cleanup when stream is disposed emitter.setDisposable(Disposables.fromRunnable(new Runnable() { @Override public void run() { RealmObject.removeChangeListener(object, listener); observableRealm.close(); objectRefs.get().releaseReference(object); } })); // Emit current value immediately emitter.onNext(object); } }, BACK_PRESSURE_STRATEGY); }
@Override public <E extends RealmModel> Observable<ObjectChange<E>> changesetsFrom(Realm realm, final E object) { final RealmConfiguration realmConfig = realm.getConfiguration(); return Observable.create(new ObservableOnSubscribe<ObjectChange<E>>() { @Override public void subscribe(final ObservableEmitter<ObjectChange<E>> emitter) throws Exception { // Gets instance to make sure that the Realm is open for as long as the // Observable is subscribed to it. final Realm observableRealm = Realm.getInstance(realmConfig); objectRefs.get().acquireReference(object); final RealmObjectChangeListener<E> listener = new RealmObjectChangeListener<E>() { @Override public void onChange(E obj, ObjectChangeSet changeSet) { if (!emitter.isDisposed()) { emitter.onNext(new ObjectChange<>(obj, changeSet)); } } }; RealmObject.addChangeListener(object, listener); // Cleanup when stream is disposed emitter.setDisposable(Disposables.fromRunnable(new Runnable() { @Override public void run() { RealmObject.removeChangeListener(object, listener); observableRealm.close(); objectRefs.get().releaseReference(object); } })); // Emit current value immediately emitter.onNext(new ObjectChange<>(object, null)); } }); }
public <T extends RealmModel> T get(Class<T> clazz, String primaryKey) { if (primaryKey == null) { primaryKey = ""; } String primaryKeyFieldName = realm.getSchema().get(clazz.getSimpleName()).getPrimaryKey(); return realm.where(clazz).equalTo(primaryKeyFieldName, primaryKey).findFirst(); }
/** * Looks for an object in Realm for the model class and primary key given. If it does not exist, * a row is created in Realm for that model and returned. * @return The model found or created. */ public <T extends RealmModel> T findOrCreate(Class<T> clazz, String primaryKey) { T model = RealmQueries.withRealm(realm).get(clazz, primaryKey); if (model == null) { model = realm.createObject(clazz, primaryKey); } return model; }
/** * Deletes an row from Realm for the model class and primary key given if it exists. * @return true if the object existed, false if not. */ public <T extends RealmModel> boolean deleteIfExists(Class<T> clazz, String primaryKey) { T model = RealmQueries.withRealm(realm).get(clazz, primaryKey); if (model == null) { return false; } RealmObject.deleteFromRealm(model); return false; }
@Override public void setup() throws Exception { super.setup(); testComponent.inject(this); query = initRealmQuery(mockRealm, TestModel.class); doNothing().when(mockRealm).beginTransaction(); doNothing().when(mockRealm).commitTransaction(); doNothing().when(mockRealm).insertOrUpdate(Matchers.any(RealmModel.class)); // noinspection unchecked doNothing().when(mockRealm).insertOrUpdate(Matchers.any(Collection.class)); }
/** * Generates a temporary primary key until the actual id is generated by the server. <b>Be * careful when calling this in a loop, if you don't save the object before calling it again, * you'll get the same id twice!</b> */ @NonNull private <T extends RealmModel> String getTempUniqueId(Class<T> clazz) { int tempId = Integer.MAX_VALUE; while (mRealm.where(clazz).equalTo("id", String.valueOf(tempId)).findAll().size() > 0) { --tempId; } return String.valueOf(tempId); }