Docs Menu

Iteration - Kotlin SDK

You can iterate through results using Flows.

Tip

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()
Note

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.

←  Sort Queries - Kotlin SDKUpdate - Kotlin SDK →
Give Feedback
© 2022 MongoDB, Inc.

About

  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2022 MongoDB, Inc.