RoomDatabaseKt

Added in 2.1.0

public final class RoomDatabaseKt


Summary

Public methods

static final @NonNull Flow<@NonNull Set<@NonNull String>>
invalidationTrackerFlow(
    @NonNull RoomDatabase receiver,
    @NonNull String tables,
    boolean emitInitialState
)

Creates a Flow that listens for changes in the database via the InvalidationTracker and emits sets of the tables that were invalidated.

static final @NonNull R
<R extends Object> withTransaction(
    @NonNull RoomDatabase receiver,
    @NonNull SuspendFunction0<@NonNull R> block
)

Calls the specified suspending block in a database transaction.

Public methods

invalidationTrackerFlow

public static final @NonNull Flow<@NonNull Set<@NonNull String>> invalidationTrackerFlow(
    @NonNull RoomDatabase receiver,
    @NonNull String tables,
    boolean emitInitialState
)

Creates a Flow that listens for changes in the database via the InvalidationTracker and emits sets of the tables that were invalidated.

The Flow will emit at least one value, a set of all the tables registered for observation to kick-start the stream unless emitInitialState is set to false.

If one of the tables to observe does not exist in the database, this Flow throws an IllegalArgumentException during collection.

The returned Flow can be used to create a stream that reacts to changes in the database:

fun getArtistTours(from: Date, to: Date): Flow<Map<Artist, TourState>> {
return db.invalidationTrackerFlow("Artist").map { _ ->
val artists = artistsDao.getAllArtists()
val tours = tourService.fetchStates(artists.map { it.id })
associateTours(artists, tours, from, to)
}
}
Parameters
@NonNull String tables

The name of the tables or views to observe.

boolean emitInitialState

Set to false if no initial emission is desired. Default value is true.

withTransaction

public static final @NonNull R <R extends Object> withTransaction(
    @NonNull RoomDatabase receiver,
    @NonNull SuspendFunction0<@NonNull R> block
)

Calls the specified suspending block in a database transaction. The transaction will be marked as successful unless an exception is thrown in the suspending block or the coroutine is cancelled.

Room will only perform at most one transaction at a time, additional transactions are queued and executed on a first come, first serve order.

Performing blocking database operations is not permitted in a coroutine scope other than the one received by the suspending block. It is recommended that all Dao function invoked within the block be suspending functions.

The internal dispatcher used to execute the given block will block an utilize a thread from Room's transaction executor until the block is complete.