kotlin-extensions / io.realm.kotlin / toFlow

toFlow

fun <T : RealmModel> T?.toFlow(): Flow<T?>

Returns a Flow that monitors changes to this RealmObject. It will emit the current RealmObject upon subscription. Object updates will continually be emitted as the RealmObject is updated - onCompletion will never be called.

Items emitted from Realm flows are frozen - see RealmObject.freeze. This means that they are immutable and can be read from any thread.

Realm flows always emit items from the thread holding the live RealmObject. This means that if you need to do further processing, it is recommended to collect the values on a computation dispatcher:

object.toFlow()
  .map { obj -> doExpensiveWork(obj) }
  .flowOn(Dispatchers.IO)
  .onEach { flowObject ->
    // ...
  }.launchIn(Dispatchers.Main)

If your would like toFlow() to stop emitting items you can instruct the flow to only emit the first item by calling kotlinx.coroutines.flow.first:

val foo = object.toFlow()
  .flowOn(context)
  .first()

Return
Kotlin Flow on which calls to onEach or collect can be made.