Room
02 / 02

Migrations, Reactive Queries & Testing

Migrations, Reactive Queries & Testing

Migrations — Don't Lose User Data

Bumping a schema version (adding a column, say) needs an explicit Migration telling Room how to transform existing data from the old schema to the new one. Without one, Room either crashes or (if configured to allow it) destructively wipes and recreates the database — losing real users' locally stored data. Schema export (writing versioned schema JSON files) gives a concrete artifact to test migrations against.

Reactive Queries with Flow

A DAO method returning Flow (or LiveData) automatically emits a new value whenever the underlying query's result would change — UI observes the database reactively rather than manually re-querying after every write. This pairs naturally with a Repository layer wrapping Room (and possibly a network source), with the local database serving as the offline-capable single source of truth kept in sync with remote data.

TypeConverters & Relations

SQLite natively stores only a handful of primitive types; a @TypeConverter tells Room how to convert a richer type (a Date, a custom enum) to and from something SQLite can actually persist. @Relation/foreign keys model one-to-many or many-to-many relationships between entities, letting one query fetch related data (a User with all their Posts) instead of hand-written joins in application code.

Testing with In-Memory Databases

Room.inMemoryDatabaseBuilder creates a database that exists only in memory for the test's duration — DAO logic runs against a real (if temporary) database with no leftover files, a standard pattern for unit/instrumented tests. For genuinely dynamic queries whose shape isn't known until runtime, Room's RawQuery/SupportSQLiteQuery approach is needed instead of a plain static @Query string.

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free