Package io.realm

Class DynamicRealm

  • All Implemented Interfaces:
    Closeable, AutoCloseable

    public class DynamicRealm
    extends Object
    DynamicRealm is a dynamic variant of Realm. This means that all access to data and/or queries are done using string based class names instead of class type references.

    This is useful during migrations or when working with string-based data like CSV or XML files.

    The same RealmConfiguration can be used to open a Realm file in both dynamic and typed mode, but modifying the schema while having both a typed and dynamic version open is highly discouraged and will most likely crash the typed Realm. During migrations only a DynamicRealm will be open.

    Dynamic Realms do not enforce schemas or schema versions and RealmMigration code is not used even if it has been defined in the RealmConfiguration.

    This means that the schema is not created or validated until a Realm has been opened in typed mode. If a Realm file is opened in dynamic mode first it will not contain any information about classes and fields, and any queries for classes defined by the schema will fail.

    See Also:
    Realm, RealmSchema
    • Field Detail

      • WRITE_EXECUTOR

        public static final io.realm.internal.async.RealmThreadPoolExecutor WRITE_EXECUTOR
        Thread pool executor used for write operations - only one thread is needed as writes cannot be parallelized.
      • sharedRealm

        public io.realm.internal.OsSharedRealm sharedRealm
      • objectContext

        public static final io.realm.BaseRealm.ThreadLocalRealmObjectContext objectContext
    • Method Detail

      • createObject

        public DynamicRealmObject createObject​(String className)
        Instantiates and adds a new object to the Realm.
        Parameters:
        className - the class name of the object to create.
        Returns:
        the new object.
        Throws:
        RealmException - if the object could not be created.
      • createObject

        public DynamicRealmObject createObject​(String className,
                                               Object primaryKeyValue)
        Creates an object with a given primary key. Classes without a primary key defined must use createObject(String)} instead.
        Returns:
        the new object. All fields will have default values for their type, except for the primary key field which will have the provided value.
        Throws:
        RealmException - if object could not be created due to the primary key being invalid.
        IllegalStateException - if the model clazz does not have an primary key defined.
        IllegalArgumentException - if the primaryKeyValue doesn't have a value that can be converted to the expected value.
      • createEmbeddedObject

        public DynamicRealmObject createEmbeddedObject​(String className,
                                                       DynamicRealmObject parentObject,
                                                       String parentProperty)
        Instantiates and adds a new embedded object to the Realm.

        This method should only be used to create objects of types marked as embedded.

        Parameters:
        className - the class name of the object to create.
        parentObject - The parent object which should hold a reference to the embedded object. If the parent property is a list the embedded object will be added to the end of that list.
        parentProperty - the property in the parent class which holds the reference.
        Returns:
        the newly created embedded object.
        Throws:
        IllegalArgumentException - if clazz is not an embedded class or if the property in the parent class cannot hold objects of the appropriate type.
        See Also:
        RealmClass.embedded()
      • where

        public RealmQuery<DynamicRealmObject> where​(String className)
        Returns a RealmQuery, which can be used to query the provided class.
        Parameters:
        className - the class of the object which is to be queried.
        Returns:
        a RealmQuery, which can be used to query for specific objects of provided type.
        Throws:
        IllegalArgumentException - if the class doesn't exist.
        See Also:
        RealmQuery
      • removeAllChangeListeners

        public void removeAllChangeListeners()
        Removes all user-defined change listeners.
        Throws:
        IllegalStateException - if you try to remove listeners from a non-Looper Thread.
        See Also:
        RealmChangeListener
      • delete

        public void delete​(String className)
        Deletes all objects of the specified class from the Realm.
        Parameters:
        className - the class for which all objects should be removed.
        Throws:
        IllegalStateException - if the Realm is closed or called from an incorrect thread.
      • asFlowable

        public Flowable<DynamicRealm> asFlowable()
        Returns an RxJava Flowable that monitors changes to this Realm. It will emit the current state when subscribed to. Items will continually be emitted as the Realm is updated - onComplete will never be called.

        Items emitted from Realm Flowables are frozen (See freeze(). This means that they are immutable and can be read on any thread.

        Realm Flowables always emit items from the thread holding the live Realm. This means that if you need to do further processing, it is recommend to observe the values on a computation scheduler:

        realm.asFlowable() .observeOn(Schedulers.computation()) .map(rxRealm -> doExpensiveWork(rxRealm)) .observeOn(AndroidSchedulers.mainThread()) .subscribe( ... );

        If you would like the asFlowable() to stop emitting items, you can instruct RxJava to only emit only the first item by using the first() operator:

         
         realm.asFlowable().first().subscribe( ... ); // You only get the results once
         
         
        Returns:
        RxJava Observable that only calls onNext. It will never call onComplete or OnError.
        See Also:
        RxJava and Realm
      • isEmpty

        public boolean isEmpty()
        Checks if this Realm contains any objects.
        Returns:
        true if empty, @{code false} otherwise.
      • getSchema

        public RealmSchema getSchema()
        Returns the mutable schema for this Realm.
        Returns:
        The RealmSchema for this Realm.
      • freeze

        public DynamicRealm freeze()
        Returns a frozen snapshot of the current Realm. This Realm can be read and queried from any thread without throwing an IllegalStateException. A frozen Realm has its own lifecycle and can be closed by calling Closeable.close(), but fully closing the Realm that spawned the frozen copy will also close the frozen Realm.

        Frozen data can be queried as normal, but trying to mutate it in any way or attempting to register any listener will throw an IllegalStateException.

        Note: Keeping a large number of Realms with different versions alive can have a negative impact on the filesize of the Realm. In order to avoid such a situation, it is possible to set RealmConfiguration.Builder.maxNumberOfActiveVersions(long).

        Returns:
        a frozen copy of this Realm.
      • setAutoRefresh

        public void setAutoRefresh​(boolean autoRefresh)
        Sets the auto-refresh status of the Realm instance.

        Auto-refresh is a feature that enables automatic update of the current Realm instance and all its derived objects (RealmResults and RealmObject instances) when a commit is performed on a Realm acting on the same file in another thread. This feature is only available if the Realm instance lives on a Looper enabled thread.

        Parameters:
        autoRefresh - true will turn auto-refresh on, false will turn it off.
        Throws:
        IllegalStateException - if called from a non-Looper thread.
      • isAutoRefresh

        public boolean isAutoRefresh()
        Retrieves the auto-refresh status of the Realm instance.
        Returns:
        the auto-refresh status.
      • isInTransaction

        public boolean isInTransaction()
        Checks if the Realm is currently in a transaction.
        Returns:
        true if inside a transaction, false otherwise.
      • writeCopyTo

        public void writeCopyTo​(File destination)
        Writes a compacted copy of the Realm to the given destination File. The resulting file can be used as initial dataset to bootstrap a local or synced Realm in other devices.

        The destination file cannot already exist.

        Note that if this is called from within a transaction it writes the current data, and not the data as it was when the last transaction was committed.

        Parameters:
        destination - file to save the Realm to.
        Throws:
        IllegalArgumentException - if destination argument is null.
        RealmFileException - if an error happened when accessing the underlying Realm file or writing to the destination file.
        IllegalStateException - if called from the UI thread.
        IllegalStateException - if not all client changes are integrated in server.
      • writeEncryptedCopyTo

        public void writeEncryptedCopyTo​(File destination,
                                         byte[] key)
        Writes a compacted and encrypted copy of the Realm to the given destination File. The resulting file can be used as initial dataset to bootstrap a local or synced Realm in other devices.

        The destination file cannot already exist.

        Note that if this is called from within a transaction it writes the current data, and not the data as it was when the last transaction was committed.

        Parameters:
        destination - file to save the Realm to.
        key - a 64-byte encryption key.
        Throws:
        IllegalArgumentException - if destination argument is null.
        RealmFileException - if an error happened when accessing the underlying Realm file or writing to the destination file.
        IllegalStateException - if called from the UI thread.
        IllegalStateException - if not all client changes are integrated in server.
      • waitForChange

        @Deprecated
        public boolean waitForChange()
        Deprecated.
        this method will be removed on the next-major release.
        Blocks the current thread until new changes to the Realm are available or stopWaitForChange() is called from another thread. Once stopWaitForChange is called, all future calls to this method will return false immediately.
        Returns:
        true if the Realm was updated to the latest version, false if it was cancelled by calling stopWaitForChange.
        Throws:
        IllegalStateException - if calling this from within a transaction or from a Looper thread.
        RealmMigrationNeededException - on typed Realm if the latest version contains incompatible schema changes.
      • stopWaitForChange

        @Deprecated
        public void stopWaitForChange()
        Deprecated.
        this method will be removed in the next-major release
        Makes any current waitForChange() return false immediately. Once this is called, all future calls to waitForChange will immediately return false.

        This method is thread-safe and should _only_ be called from another thread than the one that called waitForChange.

        Throws:
        IllegalStateException - if the Realm instance has already been closed.
      • beginTransaction

        public void beginTransaction()
        Starts a transaction which must be closed by BaseRealm.commitTransaction() or aborted by BaseRealm.cancelTransaction(). Transactions are used to atomically create, update and delete objects within a Realm.

        Before beginning a transaction, the Realm instance is updated to the latest version in order to include all changes from other threads. This update does not trigger any registered RealmChangeListener.

        It is therefore recommended to query for the items that should be modified from inside the transaction. Otherwise there is a risk that some of the results have been deleted or modified when the transaction begins.

         
         // Don't do this
         RealmResults<Person> persons = realm.where(Person.class).findAll();
         realm.beginTransaction();
         persons.first().setName("John");
         realm.commitTransaction();
        
         // Do this instead
         realm.beginTransaction();
         RealmResults<Person> persons = realm.where(Person.class).findAll();
         persons.first().setName("John");
         realm.commitTransaction();
         
         

        Notice: it is not possible to nest transactions. If you start a transaction within a transaction an exception is thrown.

        Throws:
        RealmMigrationNeededException - on typed Realm if the latest version contains incompatible schema changes.
      • commitTransaction

        public void commitTransaction()
        All changes since BaseRealm.beginTransaction() are persisted to disk and the Realm reverts back to being read-only. An event is sent to notify all other Realm instances that a change has occurred. When the event is received, the other Realms will update their objects and RealmResults to reflect the changes from this commit.
      • cancelTransaction

        public void cancelTransaction()
        Reverts all writes (created, updated, or deleted objects) made in the current write transaction and end the transaction.

        The Realm reverts back to read-only.

        Calling this when not in a transaction will throw an exception.

      • isFrozen

        public boolean isFrozen()
        Returns whether or not this Realm is frozen.
        Returns:
        true if the Realm is frozen, false if it is not.
        See Also:
        freeze()
      • getNumberOfActiveVersions

        public long getNumberOfActiveVersions()
        Returns the current number of active versions currently being held by this Realm.

        Having a large number of active versions have a negative impact on the size of the Realm file. See the FAQ for more information.

        Returns:
        number of active versions currently being held by the Realm.
        See Also:
        RealmConfiguration.Builder.maxNumberOfActiveVersions(long)
      • getPath

        public String getPath()
        Returns the canonical path to where this Realm is persisted on disk.
        Returns:
        the canonical path to the Realm file.
        See Also:
        File.getCanonicalPath()
      • getVersion

        public long getVersion()
        Returns the schema version for this Realm.
        Returns:
        the schema version for the Realm file backing this Realm.
      • close

        public void close()
        Closes the Realm instance and all its resources.

        It's important to always remember to close Realm instances when you're done with it in order not to leak memory, file descriptors or grow the size of Realm file out of measure.

        Specified by:
        close in interface AutoCloseable
        Specified by:
        close in interface Closeable
        Throws:
        IllegalStateException - if attempting to close from another thread.
      • isClosed

        public boolean isClosed()
        Checks if the Realm instance has already been closed.
        Returns:
        true if closed, false otherwise.
        Throws:
        IllegalStateException - if attempting to close from another thread.
      • getSubscriptions

        public SubscriptionSet getSubscriptions()
        Returns the subscription set associated with this Realm. The subscription set defines a set of queries that define which data is synchronized between this realm and the server.

        This method is only applicable to synchronized realms using flexible sync.

        Returns:
        the subscription set associated with this realm.
        Throws:
        IllegalStateException - if this realm is either a local realm or a partion-based synchronized realm.
      • deleteAll

        public void deleteAll()
        Deletes all objects from this Realm.
        Throws:
        IllegalStateException - if the Realm is closed or called from an incorrect thread.