public class DynamicRealm extends Object
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.
Realm
,
RealmSchema
Modifier and Type | Class and Description |
---|---|
static class |
io.realm.BaseRealm.InstanceCallback<T extends io.realm.BaseRealm>
The Callback used when reporting back the result of loading a Realm asynchronously using either
Realm.getInstanceAsync(RealmConfiguration, Realm.Callback) or
getInstanceAsync(RealmConfiguration, DynamicRealm.Callback) . |
static class |
io.realm.BaseRealm.RealmObjectContext |
static class |
DynamicRealm.Callback
The Callback used when reporting back the result of loading a Realm asynchronously using either
Realm.getInstanceAsync(RealmConfiguration, Realm.Callback) or
getInstanceAsync(RealmConfiguration, DynamicRealm.Callback) . |
static interface |
DynamicRealm.Transaction
Encapsulates a Realm transaction.
|
Modifier and Type | Field and Description |
---|---|
static io.realm.BaseRealm.ThreadLocalRealmObjectContext |
objectContext |
OsSharedRealm |
sharedRealm |
static RealmThreadPoolExecutor |
WRITE_EXECUTOR
Thread pool executor used for write operations - only one thread is needed as writes cannot
be parallelized.
|
Modifier and Type | Method and Description |
---|---|
void |
addChangeListener(RealmChangeListener<DynamicRealm> listener)
Adds a change listener to the Realm.
|
<any> |
asFlowable()
Returns an RxJava Flowable that monitors changes to this Realm.
|
void |
beginTransaction()
Starts a transaction which must be closed by
BaseRealm.commitTransaction() or aborted by
BaseRealm.cancelTransaction() . |
void |
cancelTransaction()
Reverts all writes (created, updated, or deleted objects) made in the current write transaction and end the
transaction.
|
void |
close()
Closes the Realm instance and all its resources.
|
void |
commitTransaction()
All changes since
BaseRealm.beginTransaction() are persisted to disk and the Realm reverts back to
being read-only. |
DynamicRealmObject |
createEmbeddedObject(String className,
DynamicRealmObject parentObject,
String parentProperty)
Instantiates and adds a new embedded object to the Realm.
|
DynamicRealmObject |
createObject(String className)
Instantiates and adds a new object to the Realm.
|
DynamicRealmObject |
createObject(String className,
Object primaryKeyValue)
Creates an object with a given primary key.
|
void |
delete(String className)
Deletes all objects of the specified class from the Realm.
|
void |
deleteAll()
Deletes all objects from this Realm.
|
void |
executeTransaction(DynamicRealm.Transaction transaction)
Executes a given transaction on the DynamicRealm.
|
RealmAsyncTask |
executeTransactionAsync(DynamicRealm.Transaction transaction)
Similar to
executeTransaction(Transaction) but runs asynchronously on a worker thread. |
RealmAsyncTask |
executeTransactionAsync(DynamicRealm.Transaction transaction,
DynamicRealm.Transaction.OnError onError)
Similar to
executeTransactionAsync(Transaction) , but also accepts an OnError callback. |
RealmAsyncTask |
executeTransactionAsync(DynamicRealm.Transaction transaction,
DynamicRealm.Transaction.OnSuccess onSuccess)
Similar to
executeTransactionAsync(Transaction) , but also accepts an OnSuccess callback. |
RealmAsyncTask |
executeTransactionAsync(DynamicRealm.Transaction transaction,
DynamicRealm.Transaction.OnSuccess onSuccess,
DynamicRealm.Transaction.OnError onError)
Similar to
executeTransactionAsync(Transaction) , but also accepts an OnSuccess and OnError callbacks. |
DynamicRealm |
freeze()
Returns a frozen snapshot of the current Realm.
|
RealmConfiguration |
getConfiguration()
Returns the
RealmConfiguration for this Realm. |
static DynamicRealm |
getInstance(RealmConfiguration configuration)
Realm static constructor that returns a dynamic variant of the Realm instance defined by provided
RealmConfiguration . |
static RealmAsyncTask |
getInstanceAsync(RealmConfiguration configuration,
DynamicRealm.Callback callback)
The creation of the first Realm instance per
RealmConfiguration in a process can take some time as all
initialization code need to run at that point (Setting up the Realm, validating schemas and creating initial
data). |
long |
getNumberOfActiveVersions()
Returns the current number of active versions currently being held by this Realm.
|
String |
getPath()
Returns the canonical path to where this Realm is persisted on disk.
|
RealmSchema |
getSchema()
Returns the mutable schema for this Realm.
|
long |
getVersion()
Returns the schema version for this Realm.
|
boolean |
isAutoRefresh()
Retrieves the auto-refresh status of the Realm instance.
|
boolean |
isClosed()
Checks if the
Realm instance has already been closed. |
boolean |
isEmpty()
Checks if this
Realm contains any objects. |
boolean |
isFrozen()
Returns whether or not this Realm is frozen.
|
boolean |
isInTransaction()
Checks if the Realm is currently in a transaction.
|
void |
refresh()
Refreshes the Realm instance and all the RealmResults and RealmObjects instances coming from it.
|
void |
removeAllChangeListeners()
Removes all user-defined change listeners.
|
void |
removeChangeListener(RealmChangeListener<DynamicRealm> listener)
Removes the specified change listener.
|
void |
setAutoRefresh(boolean autoRefresh)
Sets the auto-refresh status of the Realm instance.
|
void |
stopWaitForChange()
Deprecated.
this method will be removed in the next-major release
|
boolean |
waitForChange()
Deprecated.
this method will be removed on the next-major release.
|
RealmQuery<DynamicRealmObject> |
where(String className)
Returns a RealmQuery, which can be used to query the provided class.
|
void |
writeCopyTo(File destination)
Writes a compacted copy of the Realm to the given destination File.
|
void |
writeEncryptedCopyTo(File destination,
byte[] key)
Writes a compacted and encrypted copy of the Realm to the given destination File.
|
public static final RealmThreadPoolExecutor WRITE_EXECUTOR
public OsSharedRealm sharedRealm
public static final io.realm.BaseRealm.ThreadLocalRealmObjectContext objectContext
public static DynamicRealm getInstance(RealmConfiguration configuration)
RealmConfiguration
. Dynamic Realms do not care about schemaVersion and schemas, so opening a
DynamicRealm will never trigger a migration.RealmFileException
- if an error happened when accessing the underlying Realm file.IllegalArgumentException
- if configuration
argument is null
.for details on how to configure a Realm.
public static RealmAsyncTask getInstanceAsync(RealmConfiguration configuration, DynamicRealm.Callback callback)
RealmConfiguration
in a process can take some time as all
initialization code need to run at that point (Setting up the Realm, validating schemas and creating initial
data). This method places the initialization work in a background thread and deliver the Realm instance
to the caller thread asynchronously after the initialization is finished.configuration
- RealmConfiguration
used to open the Realm.callback
- invoked to return the results.RealmAsyncTask
representing a cancellable task.IllegalArgumentException
- if a null RealmConfiguration
or a null DynamicRealm.Transaction.Callback
is provided.IllegalStateException
- if it is called from a non-Looper or IntentService
thread.for more details.
public DynamicRealmObject createObject(String className)
className
- the class name of the object to create.RealmException
- if the object could not be created.public DynamicRealmObject createObject(String className, Object primaryKeyValue)
createObject(String)
} instead.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.public DynamicRealmObject createEmbeddedObject(String className, DynamicRealmObject parentObject, String parentProperty)
This method should only be used to create objects of types marked as embedded.
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.IllegalArgumentException
- if clazz
is not an embedded class or if the property
in the parent class cannot hold objects of the appropriate type.RealmClass.embedded()
public RealmQuery<DynamicRealmObject> where(String className)
className
- the class of the object which is to be queried.IllegalArgumentException
- if the class doesn't exist.RealmQuery
public void addChangeListener(RealmChangeListener<DynamicRealm> listener)
The listeners will be executed when changes are committed by this or another thread.
Realm instances are cached per thread. For that reason it is important to
remember to remove listeners again either using removeChangeListener(RealmChangeListener)
or removeAllChangeListeners()
. Not doing so can cause memory leaks.
listener
- the change listener.IllegalArgumentException
- if the change listener is null
.RealmChangeListener
,
removeChangeListener(RealmChangeListener)
,
removeAllChangeListeners()
,
refresh()
public void removeChangeListener(RealmChangeListener<DynamicRealm> listener)
listener
- the change listener to be removed.IllegalArgumentException
- if the change listener is null
.IllegalStateException
- if you try to remove a listener from a non-Looper Thread.RealmChangeListener
public void removeAllChangeListeners()
IllegalStateException
- if you try to remove listeners from a non-Looper Thread.RealmChangeListener
public void delete(String className)
className
- the class for which all objects should be removed.IllegalStateException
- if the Realm is closed or called from an incorrect thread.public void executeTransaction(DynamicRealm.Transaction transaction)
beginTransaction()
and
commitTransaction()
will be called automatically. If any exception is thrown
during the transaction cancelTransaction()
will be called instead of commitTransaction()
.
Calling this method from the UI thread will throw a RealmException
. Doing so may result in a drop of frames
or even ANRs. We recommend calling this method from a non-UI thread or using
executeTransactionAsync(Transaction)
instead.
transaction
- DynamicRealm.Transaction
to execute.IllegalArgumentException
- if the transaction
is null
.RealmException
- if called from the UI thread, unless an explicit opt-in has been declared in RealmConfiguration.Builder.allowWritesOnUiThread(boolean)
.public RealmAsyncTask executeTransactionAsync(DynamicRealm.Transaction transaction)
executeTransaction(Transaction)
but runs asynchronously on a worker thread.transaction
- DynamicRealm.Transaction
to execute.RealmAsyncTask
representing a cancellable task.IllegalArgumentException
- if the transaction
is null
, or if the Realm is opened from
another thread.public RealmAsyncTask executeTransactionAsync(DynamicRealm.Transaction transaction, DynamicRealm.Transaction.OnSuccess onSuccess)
executeTransactionAsync(Transaction)
, but also accepts an OnSuccess callback.transaction
- DynamicRealm.Transaction
to execute.onSuccess
- callback invoked when the transaction succeeds.RealmAsyncTask
representing a cancellable task.IllegalArgumentException
- if the transaction
is null
, or if the realm is opened from
another thread.public RealmAsyncTask executeTransactionAsync(DynamicRealm.Transaction transaction, DynamicRealm.Transaction.OnError onError)
executeTransactionAsync(Transaction)
, but also accepts an OnError callback.transaction
- DynamicRealm.Transaction
to execute.onError
- callback invoked when the transaction fails.RealmAsyncTask
representing a cancellable task.IllegalArgumentException
- if the transaction
is null
, or if the realm is opened from
another thread.public RealmAsyncTask executeTransactionAsync(DynamicRealm.Transaction transaction, DynamicRealm.Transaction.OnSuccess onSuccess, DynamicRealm.Transaction.OnError onError)
executeTransactionAsync(Transaction)
, but also accepts an OnSuccess and OnError callbacks.transaction
- DynamicRealm.Transaction
to execute.onSuccess
- callback invoked when the transaction succeeds.onError
- callback invoked when the transaction fails.RealmAsyncTask
representing a cancellable task.IllegalArgumentException
- if the transaction
is null
, or if the realm is opened from
another thread.public <any> asFlowable()
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
onNext
. It will never call onComplete
or OnError
.public boolean isEmpty()
Realm
contains any objects.true
if empty, @{code false} otherwise.public RealmSchema getSchema()
RealmSchema
for this Realm.public DynamicRealm freeze()
IllegalStateException
. A frozen Realm has its own lifecycle and can be closed by calling 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)
.
public void setAutoRefresh(boolean autoRefresh)
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.
autoRefresh
- true
will turn auto-refresh on, false
will turn it off.IllegalStateException
- if called from a non-Looper thread.public boolean isAutoRefresh()
public void refresh()
WARNING: Calling this on a thread with async queries will turn those queries into synchronous queries.
This means this method will throw a RealmException
if
RealmConfiguration.Builder.allowQueriesOnUiThread(boolean)
was used with true
to
obtain a Realm instance. In most cases it is better to use RealmChangeListener
s to be notified
about changes to the Realm on a given thread than it is to use this method.
IllegalStateException
- if attempting to refresh from within a transaction.RealmException
- if called from the UI thread after opting out via RealmConfiguration.Builder.allowQueriesOnUiThread(boolean)
.public boolean isInTransaction()
true
if inside a transaction, false
otherwise.public void writeCopyTo(File destination)
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.
destination
- file to save the Realm to.RealmFileException
- if an error happened when accessing the underlying Realm file or writing to the
destination file.public void writeEncryptedCopyTo(File destination, byte[] key)
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.
destination
- file to save the Realm to.key
- a 64-byte encryption key.IllegalArgumentException
- if destination argument is null.RealmFileException
- if an error happened when accessing the underlying Realm file or writing to the
destination file.@Deprecated public boolean waitForChange()
stopWaitForChange()
is called from another thread. Once stopWaitForChange is called, all future calls to this method will
return false immediately.true
if the Realm was updated to the latest version, false
if it was
cancelled by calling stopWaitForChange.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.@Deprecated public void stopWaitForChange()
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.
IllegalStateException
- if the Realm
instance has already been closed.public void beginTransaction()
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.
RealmMigrationNeededException
- on typed Realm
if the latest version contains
incompatible schema changes.public void commitTransaction()
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.public void cancelTransaction()
The Realm reverts back to read-only.
Calling this when not in a transaction will throw an exception.
public boolean isFrozen()
true
if the Realm is frozen, false
if it is not.freeze()
public long getNumberOfActiveVersions()
Having a large number of active versions have a negative impact on the size of the Realm file. See the FAQ for more information.
RealmConfiguration.Builder.maxNumberOfActiveVersions(long)
public String getPath()
File.getCanonicalPath()
public RealmConfiguration getConfiguration()
RealmConfiguration
for this Realm.RealmConfiguration
for this Realm.public long getVersion()
public void close()
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.
close
in interface Closeable
close
in interface AutoCloseable
IllegalStateException
- if attempting to close from another thread.public boolean isClosed()
Realm
instance has already been closed.true
if closed, false
otherwise.IllegalStateException
- if attempting to close from another thread.public void deleteAll()
IllegalStateException
- if the Realm is closed or called from an incorrect thread.