Read Realm Objects - Kotlin SDK
On this page
Tip
Find Object by Primary Key
To find an object with a specific primary key value, open a realm
and query the primary key field for the desired primary key value
using realm.query().
Specify the object type as a type parameter passed to query()
:
// Search equality on the primary key field name val frogs: Frog? = realm.query<Frog>("_id == $0", PRIMARY_KEY_VALUE).first().find()
Find Objects of a Type
To find all objects of a type, open a realm and pass the type as a type parameter to realm.query():
// fetch all objects of a type as a flow, asynchronously val frogsFlow: Flow<ResultsChange<Frog>> = realm.query<Frog>().asFlow() val asyncCall: Deferred<Unit> = async { frogsFlow.collect { results -> when (results) { // print out initial results is InitialResults<Frog> -> { for (frog in results.list) { Log.v("Frog: $frog") } } else -> { // do nothing on changes } } } } // fetch all objects of a type as a results collection, synchronously val frogs: RealmResults<Frog> = realm.query<Frog>().find() for(frog in frogs) { Log.v("Frog: $frog") }
Read an Object with a Dictionary Property
You can iterate and check the values of a RealmDictionary as you would a Kotlin Map.
// Find frogs who have forests with favorite ponds val frogs = realm.query<Frog>().find() val frogsWithFavoritePonds = frogs.query("favoritePondsByForest.@count > 1").find() val thisFrog = frogsWithFavoritePonds.first() Log.v("${thisFrog.name} has favorite ponds in these forests: ") // You can iterate through keys or values for (key in thisFrog.favoritePondsByForest.keys) Log.v(key) // Check if a dictionary contains a key if (thisFrog.favoritePondsByForest.containsKey("Hundred Acre Wood")) { Log.v("${thisFrog.name}'s favorite pond in Hundred Acre Wood is ${thisFrog.favoritePondsByForest["Hundred Acre Wood"]}") } // Check if a dictionary contains a value if (thisFrog.favoritePondsByForest.containsValue("Picnic Pond")) { Log.v("${thisFrog.name}'s lists Picnic Pond as a favorite pond") }
Filter Results
Filter results to retrieve a specific segment
of objects with realm.query().
In the argument of realm.query()
, use Realm Query Language to perform filtering.
Realm Query Language is a string-based query language that you can use to retrieve
objects from a realm.
Specify the object type as a type parameter passed to query()
.
For more information on constructing queries, refer to the Realm Query Language reference documentation.
// Find frogs where name is 'Michigan J. Frog' val michiganFrogs: RealmResults<Frog> = realm.query<Frog>("name = 'Michigan J. Frog'").find() // Find frogs where age > 3 AND species is 'Green' val oldGreenFrogs: RealmResults<Frog> = realm.query<Frog>("age > 3 AND species = 'green'").find()
Sort Results
To sort results, specify a sort in the query passed to
realm.query()
with the SORT
keyword. Similarly, use DISTINCT
to constrain results to unique values of a field, and
LIMIT
to cap the number of results. The SDK
provides convenience methods on RealmQuery
so you don't have
to manually write the keywords:
When used on the same query in both RQL and method form, SORT
,
DISTINCT
, and LIMIT
execute in the order they're added
to the query. This can impact the results returned from your query.
// sort in descending order, frogs with distinct owners, only the first 5, with convenience methods val convenientlyOrganizedFrogs: Flow<ResultsChange<Frog>> = realm.query<Frog>("name = 'George Washington'") .sort("age", Sort.DESCENDING).distinct("owner").limit(5).asFlow() val asyncCallConvenience: Deferred<Unit> = async { convenientlyOrganizedFrogs.collect { results -> when (results) { // print out initial results is InitialResults<Frog> -> { for (frog in results.list) { Log.v("Frog: $frog") } } else -> { // do nothing on changes } } } } // sort in descending order, frogs with distinct owners, only the first 5, using RQL val somewhatLessConvenientlyOrganizedFrogs: Flow<ResultsChange<Frog>> = realm.query<Frog>("name = 'George Washington' SORT(age DESC) DISTINCT(owner) LIMIT(5)").asFlow() val asyncCallLessConvenient: Deferred<Unit> = async { somewhatLessConvenientlyOrganizedFrogs.collect { results -> when (results) { // print out initial results is InitialResults<Frog> -> { for (frog in results.list) { Log.v("Frog: $frog") } } else -> { // do nothing on changes } } } }
Iterate Results
You can iterate through results using Flows
.
Tip
See also:
To learn more about Kotlin Flows, check out the kotlinx.coroutines documentation on Flows.
To convert your results into a Flow
, call realmQuery.asFlow().
Then iterate through the results with flow.collect():
// fetch frogs from the realm as Flowables val frogsFlow: Flow<ResultsChange<Frog>> = realm.query<Frog>().asFlow() // iterate through the flow with collect, printing each item val frogsObserver: Deferred<Unit> = async { frogsFlow.collect { results -> when (results) { // print out initial results is InitialResults<Frog> -> { for (frog in results.list) { Log.v("Frog: $frog") } } else -> { // do nothing on changes } } } } // ... some time later, cancel the flow so you can safely close the realm frogsObserver.cancel() realm.close()