kotlin-extensions / io.realm.kotlin / toChangesetFlow

toChangesetFlow

fun <T : RealmModel> T?.toChangesetFlow(): Flow<ObjectChange<T>?>

Returns a Flow that monitors changes to this RealmObject. It will emit the current RealmObject upon subscription. For each update to the RealmObject a ObjectChange consisting of a pair with the RealmObject and its corresponding ObjectChangeSet will be sent. The changeset will be null the first time the RealmObject is emitted.

The RealmObject will continually be emitted as it is updated. This flow will never complete.

Items emitted are frozen (see RealmObject.freeze). This means that they are immutable and can be read on any thread.

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

object.toChangesetFlow()
  .map { change -> doExpensiveWork(change) }
  .flowOn(Dispatchers.IO)
  .onEach { change ->
    // ...
  }.launchIn(Dispatchers.Main)

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

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

Exceptions

UnsupportedOperationException - if the required coroutines framework is not on the classpath or the corresponding Realm instance doesn't support flows.

IllegalStateException - if the Realm wasn't opened on a Looper thread.

Return
Kotlin Flow that will never complete.