Search in sources :

Example 46 with RealmConfiguration

use of io.realm.RealmConfiguration in project realm-java by realm.

the class RealmObservableFactory method changesetsFrom.

@Override
public <E extends RealmModel> Observable<ObjectChange<E>> changesetsFrom(Realm realm, final E object) {
    if (realm.isFrozen()) {
        return Observable.just(new ObjectChange<E>(object, null));
    }
    final RealmConfiguration realmConfig = realm.getConfiguration();
    Scheduler scheduler = getScheduler();
    return Observable.create(new ObservableOnSubscribe<ObjectChange<E>>() {

        @Override
        public void subscribe(final ObservableEmitter<ObjectChange<E>> emitter) {
            // If the Realm has been closed, just create an empty Observable because we assume it is going to be disposed shortly.
            if (!RealmObject.isValid(object))
                return;
            // 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<>(returnFrozenObjects ? RealmObject.freeze(obj) : obj, changeSet));
                    }
                }
            };
            RealmObject.addChangeListener(object, listener);
            // Cleanup when stream is disposed
            emitter.setDisposable(Disposables.fromRunnable(new Runnable() {

                @Override
                public void run() {
                    if (!observableRealm.isClosed()) {
                        RealmObject.removeChangeListener(object, listener);
                        observableRealm.close();
                    }
                    objectRefs.get().releaseReference(object);
                }
            }));
            // Emit current value immediately
            emitter.onNext(new ObjectChange<>(returnFrozenObjects ? RealmObject.freeze(object) : object, null));
        }
    }).subscribeOn(scheduler).unsubscribeOn(scheduler);
}
Also used : RealmObjectChangeListener(io.realm.RealmObjectChangeListener) Scheduler(io.reactivex.Scheduler) ObjectChangeSet(io.realm.ObjectChangeSet) RealmConfiguration(io.realm.RealmConfiguration) Realm(io.realm.Realm) DynamicRealm(io.realm.DynamicRealm)

Example 47 with RealmConfiguration

use of io.realm.RealmConfiguration in project realm-java by realm.

the class RealmObservableFactory method from.

@Override
public Flowable<DynamicRealmObject> from(DynamicRealm realm, final DynamicRealmObject object) {
    if (realm.isFrozen()) {
        return Flowable.just(object);
    }
    final RealmConfiguration realmConfig = realm.getConfiguration();
    Scheduler scheduler = getScheduler();
    return Flowable.create(new FlowableOnSubscribe<DynamicRealmObject>() {

        @Override
        public void subscribe(final FlowableEmitter<DynamicRealmObject> emitter) {
            // If the Realm has been closed, just create an empty Observable because we assume it is going to be disposed shortly.
            if (realm.isClosed())
                return;
            // Gets instance to make sure that the Realm is open for as long as the
            // Observable is subscribed to it.
            final DynamicRealm observableRealm = DynamicRealm.getInstance(realmConfig);
            objectRefs.get().acquireReference(object);
            final RealmChangeListener<DynamicRealmObject> listener = new RealmChangeListener<DynamicRealmObject>() {

                @Override
                public void onChange(DynamicRealmObject obj) {
                    if (!emitter.isCancelled()) {
                        emitter.onNext(returnFrozenObjects ? RealmObject.freeze(obj) : obj);
                    }
                }
            };
            RealmObject.addChangeListener(object, listener);
            // Cleanup when stream is disposed
            emitter.setDisposable(Disposables.fromRunnable(new Runnable() {

                @Override
                public void run() {
                    if (!observableRealm.isClosed()) {
                        RealmObject.removeChangeListener(object, listener);
                        observableRealm.close();
                    }
                    objectRefs.get().releaseReference(object);
                }
            }));
            // Emit current value immediately
            emitter.onNext(returnFrozenObjects ? RealmObject.freeze(object) : object);
        }
    }, BACK_PRESSURE_STRATEGY).subscribeOn(scheduler).unsubscribeOn(scheduler);
}
Also used : RealmConfiguration(io.realm.RealmConfiguration) DynamicRealmObject(io.realm.DynamicRealmObject) RealmChangeListener(io.realm.RealmChangeListener) Scheduler(io.reactivex.Scheduler) DynamicRealm(io.realm.DynamicRealm)

Example 48 with RealmConfiguration

use of io.realm.RealmConfiguration in project realm-java by realm.

the class RealmObservableFactory method from.

@Override
public <E> Flowable<RealmList<E>> from(DynamicRealm realm, final RealmList<E> list) {
    if (realm.isFrozen()) {
        return Flowable.just(list);
    }
    final RealmConfiguration realmConfig = realm.getConfiguration();
    Scheduler scheduler = getScheduler();
    return Flowable.create(new FlowableOnSubscribe<RealmList<E>>() {

        @Override
        public void subscribe(final FlowableEmitter<RealmList<E>> emitter) {
            // If the Realm has been closed, just create an empty Observable because we assume it is going to be disposed shortly.
            if (!list.isValid())
                return;
            // Gets instance to make sure that the Realm is open for as long as the
            // Observable is subscribed to it.
            final DynamicRealm observableRealm = DynamicRealm.getInstance(realmConfig);
            listRefs.get().acquireReference(list);
            final RealmChangeListener<RealmList<E>> listener = new RealmChangeListener<RealmList<E>>() {

                @Override
                public void onChange(RealmList<E> list) {
                    if (!list.isValid()) {
                        // Terminate stream if list is no longer valid. This indicates
                        // the parent object has been deleted, so no further updates
                        // will be coming.
                        emitter.onComplete();
                        return;
                    }
                    if (!emitter.isCancelled()) {
                        emitter.onNext(returnFrozenObjects ? list.freeze() : list);
                    }
                }
            };
            list.addChangeListener(listener);
            // Cleanup when stream is disposed
            emitter.setDisposable(Disposables.fromRunnable(new Runnable() {

                @Override
                public void run() {
                    if (!observableRealm.isClosed()) {
                        list.removeChangeListener(listener);
                        observableRealm.close();
                    }
                    listRefs.get().releaseReference(list);
                }
            }));
            // Emit current value immediately
            emitter.onNext(returnFrozenObjects ? list.freeze() : list);
        }
    }, BACK_PRESSURE_STRATEGY).subscribeOn(scheduler).unsubscribeOn(scheduler);
}
Also used : RealmConfiguration(io.realm.RealmConfiguration) RealmChangeListener(io.realm.RealmChangeListener) RealmList(io.realm.RealmList) Scheduler(io.reactivex.Scheduler) DynamicRealm(io.realm.DynamicRealm)

Example 49 with RealmConfiguration

use of io.realm.RealmConfiguration in project realm-java by realm.

the class SyncObjectServerFacade method getSyncConfigurationOptions.

@Override
public Object[] getSyncConfigurationOptions(RealmConfiguration config) {
    if (config instanceof SyncConfiguration) {
        SyncConfiguration syncConfig = (SyncConfiguration) config;
        User user = syncConfig.getUser();
        App app = user.getApp();
        String rosServerUrl = syncConfig.getServerUrl().toString();
        String rosUserIdentity = user.getId();
        String syncRealmAuthUrl = user.getApp().getConfiguration().getBaseUrl().toString();
        String rosUserProvider = user.getProviderType().getId();
        String syncUserRefreshToken = user.getRefreshToken();
        String syncUserAccessToken = user.getAccessToken();
        String deviceId = user.getDeviceId();
        byte sessionStopPolicy = syncConfig.getSessionStopPolicy().getNativeValue();
        String urlPrefix = syncConfig.getUrlPrefix();
        String customAuthorizationHeaderName = app.getConfiguration().getAuthorizationHeaderName();
        Map<String, String> customHeaders = app.getConfiguration().getCustomRequestHeaders();
        SyncClientResetStrategy clientResetStrategy = syncConfig.getSyncClientResetStrategy();
        // undefined value
        byte clientResetMode = -1;
        if (clientResetStrategy instanceof ManuallyRecoverUnsyncedChangesStrategy) {
            clientResetMode = OsRealmConfig.CLIENT_RESYNC_MODE_MANUAL;
        } else if (clientResetStrategy instanceof DiscardUnsyncedChangesStrategy) {
            clientResetMode = OsRealmConfig.CLIENT_RESYNC_MODE_DISCARD_LOCAL;
        }
        BeforeClientResetHandler beforeClientResetHandler = (localPtr, osRealmConfig) -> {
            NativeContext.execute(nativeContext -> {
                Realm before = realmInstanceFactory.createInstance(new OsSharedRealm(localPtr, osRealmConfig, nativeContext));
                ((DiscardUnsyncedChangesStrategy) clientResetStrategy).onBeforeReset(before);
            });
        };
        AfterClientResetHandler afterClientResetHandler = (localPtr, afterPtr, osRealmConfig) -> {
            NativeContext.execute(nativeContext -> {
                Realm before = realmInstanceFactory.createInstance(new OsSharedRealm(localPtr, osRealmConfig, nativeContext));
                Realm after = realmInstanceFactory.createInstance(new OsSharedRealm(afterPtr, osRealmConfig, nativeContext));
                ((DiscardUnsyncedChangesStrategy) clientResetStrategy).onAfterReset(before, after);
            });
        };
        long appNativePointer;
        // access it.
        try {
            if (osAppField == null) {
                synchronized (SyncObjectServerFacade.class) {
                    if (osAppField == null) {
                        Field field = App.class.getDeclaredField("osApp");
                        field.setAccessible(true);
                        osAppField = field;
                    }
                }
            }
            OsApp osApp = (OsApp) osAppField.get(app);
            appNativePointer = osApp.getNativePtr();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        // TODO Simplify. org.bson serialization only allows writing full documents, so the partition
        // key is embedded in a document with key 'value' and unwrapped in JNI.
        String encodedPartitionValue = null;
        if (syncConfig.isPartitionBasedSyncConfiguration()) {
            BsonValue partitionValue = syncConfig.getPartitionValue();
            switch(partitionValue.getBsonType()) {
                case STRING:
                case OBJECT_ID:
                case INT32:
                case INT64:
                case BINARY:
                case NULL:
                    encodedPartitionValue = JniBsonProtocol.encode(partitionValue, AppConfiguration.DEFAULT_BSON_CODEC_REGISTRY);
                    break;
                default:
                    throw new IllegalArgumentException("Unsupported type: " + partitionValue);
            }
        }
        int i = 0;
        Object[] configObj = new Object[SYNC_CONFIG_OPTIONS];
        configObj[i++] = rosUserIdentity;
        configObj[i++] = rosUserProvider;
        configObj[i++] = rosServerUrl;
        configObj[i++] = syncRealmAuthUrl;
        configObj[i++] = syncUserRefreshToken;
        configObj[i++] = syncUserAccessToken;
        configObj[i++] = deviceId;
        configObj[i++] = sessionStopPolicy;
        configObj[i++] = urlPrefix;
        configObj[i++] = customAuthorizationHeaderName;
        configObj[i++] = customHeaders;
        configObj[i++] = clientResetMode;
        configObj[i++] = beforeClientResetHandler;
        configObj[i++] = afterClientResetHandler;
        configObj[i++] = encodedPartitionValue;
        configObj[i++] = app.getSync();
        configObj[i++] = appNativePointer;
        return configObj;
    } else {
        return new Object[SYNC_CONFIG_OPTIONS];
    }
}
Also used : OsApp(io.realm.internal.objectstore.OsApp) App(io.realm.mongodb.App) Context(android.content.Context) SubscriptionSet(io.realm.mongodb.sync.SubscriptionSet) DownloadingRealmInterruptedException(io.realm.exceptions.DownloadingRealmInterruptedException) RealmException(io.realm.exceptions.RealmException) OsApp(io.realm.internal.objectstore.OsApp) DiscardUnsyncedChangesStrategy(io.realm.mongodb.sync.DiscardUnsyncedChangesStrategy) BsonValue(org.bson.BsonValue) MutableSubscriptionSet(io.realm.mongodb.sync.MutableSubscriptionSet) AppConfiguration(io.realm.mongodb.AppConfiguration) SuppressLint(android.annotation.SuppressLint) Map(java.util.Map) ManuallyRecoverUnsyncedChangesStrategy(io.realm.mongodb.sync.ManuallyRecoverUnsyncedChangesStrategy) User(io.realm.mongodb.User) Method(java.lang.reflect.Method) ConnectivityManager(android.net.ConnectivityManager) App(io.realm.mongodb.App) SyncClientResetStrategy(io.realm.mongodb.sync.SyncClientResetStrategy) Realm(io.realm.Realm) NetworkStateReceiver(io.realm.internal.network.NetworkStateReceiver) OsAsyncOpenTask(io.realm.internal.objectstore.OsAsyncOpenTask) IntentFilter(android.content.IntentFilter) AndroidCapabilities(io.realm.internal.android.AndroidCapabilities) Field(java.lang.reflect.Field) InvocationTargetException(java.lang.reflect.InvocationTargetException) JniBsonProtocol(io.realm.internal.jni.JniBsonProtocol) TimeUnit(java.util.concurrent.TimeUnit) RealmConfiguration(io.realm.RealmConfiguration) SyncConfiguration(io.realm.mongodb.sync.SyncConfiguration) Sync(io.realm.mongodb.sync.Sync) User(io.realm.mongodb.User) Field(java.lang.reflect.Field) Realm(io.realm.Realm) SyncConfiguration(io.realm.mongodb.sync.SyncConfiguration) DiscardUnsyncedChangesStrategy(io.realm.mongodb.sync.DiscardUnsyncedChangesStrategy) DownloadingRealmInterruptedException(io.realm.exceptions.DownloadingRealmInterruptedException) RealmException(io.realm.exceptions.RealmException) InvocationTargetException(java.lang.reflect.InvocationTargetException) SuppressLint(android.annotation.SuppressLint) ManuallyRecoverUnsyncedChangesStrategy(io.realm.mongodb.sync.ManuallyRecoverUnsyncedChangesStrategy) SyncClientResetStrategy(io.realm.mongodb.sync.SyncClientResetStrategy) OsApp(io.realm.internal.objectstore.OsApp) BsonValue(org.bson.BsonValue)

Example 50 with RealmConfiguration

use of io.realm.RealmConfiguration in project realm-java by realm.

the class RealmObservableFactory method from.

@Override
public <E extends RealmModel> Flowable<E> from(final Realm realm, final E object) {
    if (realm.isFrozen()) {
        return Flowable.just(object);
    }
    final RealmConfiguration realmConfig = realm.getConfiguration();
    Scheduler scheduler = getScheduler();
    return Flowable.create(new FlowableOnSubscribe<E>() {

        @Override
        public void subscribe(final FlowableEmitter<E> emitter) {
            // If the Realm has been closed, just create an empty Observable because we assume it is going to be disposed shortly.
            if (realm.isClosed())
                return;
            // 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(returnFrozenObjects ? RealmObject.freeze(obj) : obj);
                    }
                }
            };
            RealmObject.addChangeListener(object, listener);
            // Cleanup when stream is disposed
            emitter.setDisposable(Disposables.fromRunnable(new Runnable() {

                @Override
                public void run() {
                    if (!observableRealm.isClosed()) {
                        RealmObject.removeChangeListener(object, listener);
                        observableRealm.close();
                    }
                    objectRefs.get().releaseReference(object);
                }
            }));
            // Emit current value immediately
            emitter.onNext(returnFrozenObjects ? RealmObject.freeze(object) : object);
        }
    }, BACK_PRESSURE_STRATEGY).subscribeOn(scheduler).unsubscribeOn(scheduler);
}
Also used : RealmConfiguration(io.realm.RealmConfiguration) RealmChangeListener(io.realm.RealmChangeListener) Scheduler(io.reactivex.Scheduler) Realm(io.realm.Realm) DynamicRealm(io.realm.DynamicRealm)

Aggregations

RealmConfiguration (io.realm.RealmConfiguration)64 Realm (io.realm.Realm)20 DynamicRealm (io.realm.DynamicRealm)17 Scheduler (io.reactivex.Scheduler)14 RealmChangeListener (io.realm.RealmChangeListener)8 BeforeExperiment (dk.ilios.spanner.BeforeExperiment)6 Before (org.junit.Before)5 DynamicRealmObject (io.realm.DynamicRealmObject)4 RealmList (io.realm.RealmList)4 RealmResults (io.realm.RealmResults)4 ArrayList (java.util.ArrayList)4 Test (org.junit.Test)4 Context (android.content.Context)3 OrderedCollectionChangeSet (io.realm.OrderedCollectionChangeSet)3 OrderedRealmCollectionChangeListener (io.realm.OrderedRealmCollectionChangeListener)3 RealmObjectSchema (io.realm.RealmObjectSchema)3 AllTypes (io.realm.entities.AllTypes)3 IntentFilter (android.content.IntentFilter)2 LinearLayout (android.widget.LinearLayout)2 RealmSchema (io.realm.RealmSchema)2