Class Realm

The Realm class is the storage and transactional manager of your object persistent store. It is in charge of creating
instances of your RealmObjects. Objects within a Realm can be queried and read at any time. Creating, modifying, and
deleting objects must be done while inside a transaction. See executeTransaction(Transaction)

The transactions ensure that multiple instances (on multiple threads) can access the same objects in a consistent
state with full ACID guarantees.

It is important to remember to call the close() method when done with a Realm instance. Failing to do so can
lead to OutOfMemoryError as the native resources cannot be freed.

Realm instances cannot be used across different threads. This means that you have to open an instance on each thread
you want to use Realm. Realm instances are cached automatically per thread using reference counting, so as long as
the reference count doesn't reach zero, calling getInstance(RealmConfiguration) will just return the cached
Realm and should be considered a lightweight operation.

For the UI thread this means that opening and closing Realms should occur in either onCreate/onDestroy or
onStart/onStop.

Realm instances coordinate their state across threads using the Handler mechanism. This also means
that Realm instances on threads without a Looper cannot receive updates unless waitForChange()
is manually called.

A standard pattern for working with Realm in Android activities can be seen below:

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).

Field Detail

DEFAULT_REALM_NAME

objectContext

public static final io.realm.BaseRealm.ThreadLocalRealmObjectContext objectContext

Method Detail

asObservable

public <any> asObservable()

Returns an RxJava Observable 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.

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

realm.asObservable().first().subscribe( ... ) // You only get the results once

Returns:

RxJava Observable that only calls onNext. It will never call onComplete or OnError.

getInstanceAsync

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). 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.

createOrUpdateAllFromJson

Tries to update a list of existing objects identified by their primary key with new JSON data. If an existing
object could not be found in the Realm, a new object will be created. This must happen within a transaction.
If updating a RealmObject and a field is not found in the JSON object, that field will not be updated. If
a new RealmObject is created and a field is not found in the JSON object, that field will be assigned the
default value for the field type.

Parameters:

clazz - type of RealmObject to create or update. It must have a primary key defined.

createAllFromJson

Creates a Realm object for each object in a JSON array. This must be done within a transaction.
JSON properties with unknown properties will be ignored. If a RealmObject field is not present in the
JSON object the RealmObject field will be set to the default value for that type.

Parameters:

clazz - type of Realm objects to create.

json - the JSON array as a String where each object can map to the specified class.

createOrUpdateAllFromJson

Tries to update a list of existing objects identified by their primary key with new JSON data. If an existing
object could not be found in the Realm, a new object will be created. This must happen within a transaction.
If updating a RealmObject and a field is not found in the JSON object, that field will not be updated.
If a new RealmObject is created and a field is not found in the JSON object, that field will be assigned
the default value for the field type.

Parameters:

clazz - type of RealmObject to create or update. It must have a primary key defined.

createAllFromJson

Creates a Realm object for each object in a JSON array. This must be done within a transaction.
JSON properties with unknown properties will be ignored. If a RealmObject field is not present in the
JSON object the RealmObject field will be set to the default value for that type.

This API is only available in API level 11 or later.

Parameters:

clazz - type of Realm objects created.

inputStream - the JSON array as a InputStream. All objects in the array must be of the specified class.

createOrUpdateAllFromJson

Tries to update a list of existing objects identified by their primary key with new JSON data. If an existing
object could not be found in the Realm, a new object will be created. This must happen within a transaction.
If updating a RealmObject and a field is not found in the JSON object, that field will not be updated.
If a new RealmObject is created and a field is not found in the JSON object, that field will be assigned
the default value for the field type.

This API is only available in API level 11 or later.

Parameters:

clazz - type of RealmObject to create or update. It must have a primary key defined.

createObjectFromJson

Creates a Realm object pre-filled with data from a JSON object. This must be done inside a transaction. JSON
properties with unknown properties will be ignored. If a RealmObject field is not present in the JSON
object the RealmObject field will be set to the default value for that type.

createOrUpdateObjectFromJson

Tries to update an existing object defined by its primary key with new JSON data. If no existing object could be
found a new object will be saved in the Realm. This must happen within a transaction. If updating a RealmObject
and a field is not found in the JSON object, that field will not be updated. If a new RealmObject is
created and a field is not found in the JSON object, that field will be assigned the default value for the field type.

Parameters:

clazz - Type of RealmObject to create or update. It must have a primary key defined.

createObjectFromJson

Creates a Realm object pre-filled with data from a JSON object. This must be done inside a transaction. JSON
properties with unknown properties will be ignored. If a RealmObject field is not present in the JSON
object the RealmObject field will be set to the default value for that type.

createOrUpdateObjectFromJson

Tries to update an existing object defined by its primary key with new JSON data. If no existing object could be
found a new object will be saved in the Realm. This must happen within a transaction. If updating a
RealmObject and a field is not found in the JSON object, that field will not be updated. If a new
RealmObject is created and a field is not found in the JSON object, that field will be assigned the
default value for the field type.

Parameters:

clazz - type of RealmObject to create or update. It must have a primary key defined.

createObjectFromJson

Creates a Realm object pre-filled with data from a JSON object. This must be done inside a transaction. JSON
properties with unknown properties will be ignored. If a RealmObject field is not present in the JSON
object the RealmObject field will be set to the default value for that type.

createOrUpdateObjectFromJson

Tries to update an existing object defined by its primary key with new JSON data. If no existing object could be
found a new object will be saved in the Realm. This must happen within a transaction. If updating a
RealmObject and a field is not found in the JSON object, that field will not be updated. If a new
RealmObject is created and a field is not found in the JSON object, that field will be assigned the
default value for the field type.

This API is only available in API level 11 or later.

Parameters:

clazz - type of RealmObject to create or update. It must have a primary key defined.

copyToRealm

Copies a RealmObject to the Realm instance and returns the copy. Any further changes to the original RealmObject
will not be reflected in the Realm copy. This is a deep copy, so all referenced objects will be copied. Objects
already in this Realm will be ignored.

Please note, copying an object will copy all field values. Any unset field in this and child objects will be
set to their default value if not provided.

copyToRealmOrUpdate

Updates an existing RealmObject that is identified by the same PrimaryKey or creates
a new copy if no existing object could be found. This is a deep copy or update i.e., all referenced objects will be
either copied or updated.

Please note, copying an object will copy all field values. Any unset field in the object and child objects will be
set to their default value if not provided.

copyToRealm

Copies a collection of RealmObjects to the Realm instance and returns their copy. Any further changes to the
original RealmObjects will not be reflected in the Realm copies. This is a deep copy i.e., all referenced objects
will be copied. Objects already in this Realm will be ignored.

Please note, copying an object will copy all field values. Any unset field in the objects and child objects will be
set to their default value if not provided.

Parameters:

objects - the RealmObjects to copy to the Realm.

Returns:

a list of the the converted RealmObjects that all has their properties managed by the Realm.

Throws:

RealmException - if any of the objects has already been added to Realm.

insert

Inserts a list of an unmanaged RealmObjects. This is generally faster than copyToRealm(Iterable) since it
doesn't return the inserted elements, and performs minimum allocations and checks.
After being inserted any changes to the original objects will not be persisted.

Please note:

We don't check if the provided objects are already managed or not, so inserting a managed object might duplicate it.
Duplication will only happen if the object doesn't have a primary key. Objects with primary keys will never get duplicated.

insert

Inserts an unmanaged RealmObject. This is generally faster than copyToRealm(RealmModel) since it
doesn't return the inserted elements, and performs minimum allocations and checks.
After being inserted any changes to the original object will not be persisted.

Please note:

We don't check if the provided objects are already managed or not, so inserting a managed object might duplicate it.
Duplication will only happen if the object doesn't have a primary key. Objects with primary keys will never get duplicated.

insertOrUpdate

Inserts or updates a list of unmanaged RealmObjects. This is generally faster than
copyToRealmOrUpdate(Iterable) since it doesn't return the inserted elements, and performs minimum
allocations and checks.
After being inserted any changes to the original objects will not be persisted.

Please note:

We don't check if the provided objects are already managed or not, so inserting a managed object might duplicate it.
Duplication will only happen if the object doesn't have a primary key. Objects with primary keys will never get duplicated.

insertOrUpdate

Inserts or updates an unmanaged RealmObject. This is generally faster than
copyToRealmOrUpdate(RealmModel) since it doesn't return the inserted elements, and performs minimum
allocations and checks.
After being inserted any changes to the original object will not be persisted.

Please note:

We don't check if the provided objects are already managed or not, so inserting a managed object might duplicate it.
Duplication will only happen if the object doesn't have a primary key. Objects with primary keys will never get duplicated.

copyToRealmOrUpdate

Updates a list of existing RealmObjects that is identified by their PrimaryKey or
creates a new copy if no existing object could be found. This is a deep copy or update i.e., all referenced
objects will be either copied or updated.

Please note, copying an object will copy all field values. Any unset field in the objects and child objects will be
set to their default value if not provided.

copyFromRealm

Makes an unmanaged in-memory copy of already persisted RealmObjects. This is a deep copy that will copy all
referenced objects.

The copied objects are all detached from Realm and they will no longer be automatically updated. This means
that the copied objects might contain data that are no longer consistent with other managed Realm objects.

*WARNING*: Any changes to copied objects can be merged back into Realm using
copyToRealmOrUpdate(RealmModel), but all fields will be overridden, not just those that were changed.
This includes references to other objects, and can potentially override changes made by other threads.

copyFromRealm

Makes an unmanaged in-memory copy of already persisted RealmObjects. This is a deep copy that will copy all
referenced objects up to the defined depth.

The copied objects are all detached from Realm and they will no longer be automatically updated. This means
that the copied objects might contain data that are no longer consistent with other managed Realm objects.

*WARNING*: Any changes to copied objects can be merged back into Realm using
copyToRealmOrUpdate(Iterable), but all fields will be overridden, not just those that were changed.
This includes references to other objects even though they might be null due to maxDepth being
reached. This can also potentially override changes made by other threads.

Type Parameters:

E - type of object.

Parameters:

realmObjects - RealmObjects to copy.

maxDepth - limit of the deep copy. All references after this depth will be null. Starting depth is
0.

copyFromRealm

Makes an unmanaged in-memory copy of an already persisted RealmObject. This is a deep copy that will copy
all referenced objects.

The copied object(s) are all detached from Realm and they will no longer be automatically updated. This means
that the copied objects might contain data that are no longer consistent with other managed Realm objects.

*WARNING*: Any changes to copied objects can be merged back into Realm using
copyToRealmOrUpdate(RealmModel), but all fields will be overridden, not just those that were changed.
This includes references to other objects, and can potentially override changes made by other threads.

copyFromRealm

Makes an unmanaged in-memory copy of an already persisted RealmObject. This is a deep copy that will copy
all referenced objects up to the defined depth.

The copied object(s) are all detached from Realm and they will no longer be automatically updated. This means
that the copied objects might contain data that are no longer consistent with other managed Realm objects.

*WARNING*: Any changes to copied objects can be merged back into Realm using
copyToRealmOrUpdate(RealmModel), but all fields will be overridden, not just those that were changed.
This includes references to other objects even though they might be null due to maxDepth being
reached. This can also potentially override changes made by other threads.

compactRealm

Compacts a Realm file. A Realm file usually contain free/unused space.
This method removes this free space and the file size is thereby reduced.
Objects within the Realm files are untouched.

The file must be closed before this method is called, otherwise false will be returned.
The file system should have free space for at least a copy of the Realm file.
The Realm file is left untouched if any file operation fails.

getDefaultModule

Returns the default Realm module. This module contains all Realm classes in the current project, but not those
from library or project dependencies. Realm classes in these should be exposed using their own module.

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.

isAutoRefresh

refresh

public void refresh()

Refreshes the Realm instance and all the RealmResults and RealmObjects instances coming from it.
It also calls any listeners associated with the Realm if neeeded.

WARNING: Calling this on a thread with async queries will turn those queries into synchronous queries.
In most cases it is better to use RealmChangeListeners to be notified about changes to the
Realm on a given thread than it is to use this method.

RealmFileException - if an error happened when accessing the underlying Realm file or writing to the
destination file.

waitForChange

public boolean waitForChange()

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.

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.

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.