Skip to main content

Iteration

You can iterate through results using Flows.

Learn About Flows

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()
find() is Synchronous

You can also iterate through results returned via find(). find() runs a synchronous query on the thread it is called from. As a result, avoid using find() on the UI thread or in logic that could delay the UI thread. Prefer asFlow() in time sensitive environments.