asFlow

fun <T : RealmModel> RealmQueryBuilder<T>.asFlow(dispatcher: RealmDispatcherProvider = { RealmDispatcher() }): Flow<List<T>>

Returns a Flow of list of R generated using transform on the RealmModel instances satisfying the current RealmQuery. The flow emits new list of RealmModel instances whenever RealmQuery results has a change. The returned items can be safely passed around threads since they are unmanaged due to usage of RealmCopyTransform which uses Realm.copyFromRealm to create non managed instances.

The RealmQuery is executed using a Realm obtained with DefaultRealm and it stays active for the duration of the active collection of the flow.

The implementation uses the RealmDispatcher instance to run the query and observe changes. By default a new instance of RealmDispatcher is created with dispatcher but this can be customized by passing a custom instance. When flow collection is cancelled, the RealmDispatcher is disposed to release resources by calling RealmDispatcher.close.

Note: For large nested RealmModels consider using overloaded method that accepts RealmModelTransform to run a custom transform function to generate a subset of data from RealmModel instance.

Usage:

open class Person(var name: String = "", val age: Int = 0) : RealmObject

val persons: Flow<List<Person> = RealmQuery { where<Person>() }.asFlow()

See also

RealmQueryBuilder.asFlow
fun <T : RealmModel, R> RealmQueryBuilder<T>.asFlow(dispatcher: RealmDispatcherProvider = { RealmDispatcher() }, transform: RealmModelTransform<T, R>): Flow<List<R>>

Returns a Flow of list of R generated using transform on the RealmModel instances satisfying the current RealmQuery. The flow emits new list of RealmModel instances whenever RealmQuery results has a change. The returned items can be safely passed around threads since they are unmanaged as long the transform does not return managed instances. For correct implementation of transform see RealmCopyTransform.

The RealmQuery is executed using a Realm obtained with DefaultRealm and it stays active for the duration of the active collection of the flow.

The implementation uses the RealmDispatcher instance to run the query and observe changes. By default a new instance of RealmDispatcher is created with dispatcher but this can be customized by passing a custom instance. When flow collection is cancelled, the RealmDispatcher is disposed to release resources by calling RealmDispatcher.close.

Notes: Use transform to map the managed RealmModel instance to a non managed one of type R. It is a good practice to only read the desired properties from RealmModel as reading the whole object brings entire object into application memory.

Usage:

open class Person(var name: String = "", val age: Int = 0) : RealmObject
data class PersonName(val name: String)

val personNames: Flow<List<PersonName> = RealmQuery { where<Person>() }
.asFlow { PersonName(it.name) }

See also

RealmQueryBuilder.asFlow