asCallbackFlow

Converts the KQLiteCursor into a cold Flow that emits the cursor whenever the underlying database tables are updated.

It observes INSERT, UPDATE and DELETED onto the specified table this is used to create cursor.

If the cursor is not created using SELECT SelectStatement or has no associated tables in it, the resulting flow will emit the cursor once and then complete.

It does not re-emit the cursor for queries other than SELECT statement.

Example

fun selectActiveContacts(): KQLiteCursor {
return TblContact
.select()
.where { it.deleted NOT_EQ true }
.execute()
}

val uiState: StateFlow<ContactUiState> =
selectActiveContacts()
.asCallbackFlow()
.mapToList { TblContact.mapper(it) }
.map { ContactUiState.Success(it) }
.flowOn(Dispatchers.IO)
.stateIn(
viewModelScope,
SharingStarted.WhileSubscribed(5000),
ContactUiState.Loading
)

For reactive cursors, this flow:

  1. Emits the current cursor immediately upon collection.

  2. Registers a listener on the database tables associated with the cursor.

  3. Re-emits the cursor whenever a change is detected in those tables.

  4. Automatically unregisters the listener when the flow collection is canceled.

NOTE: This will reexecute and reload new data on every flow emit of SELECT query.

Return

A Flow of KQLiteCursor that triggers on database changes for SELECT statement.