Realm Database Setup in Mobile Applications
Realm is not just a SQLite wrapper. It's object database with its own engine storing data in binary .realm format and working with objects directly, without ORM layer. In practice this means reading 10,000 objects via Results<T> is O(1) memory-wise because results are lazy and don't materialize until accessed.
Connection and Basic Configuration
For iOS use RealmSwift (SPM or CocoaPods), for Android use io.realm.kotlin Kotlin SDK. Old Java SDK (io.realm:realm-android) is officially deprecated — don't use in new projects.
// Android: Realm Kotlin SDK initialization
val config = RealmConfiguration.Builder(
schema = setOf(User::class, Order::class, Product::class)
)
.name("app.realm")
.schemaVersion(3)
.migration(AppMigration()) // if schemaVersion > 0
.build()
val realm = Realm.open(config)
// iOS: open Realm with configuration
let config = Realm.Configuration(
fileURL: Realm.Configuration.defaultConfiguration.fileURL!
.deletingLastPathComponent()
.appendingPathComponent("app.realm"),
schemaVersion: 3,
migrationBlock: { migration, oldVersion in
if oldVersion < 2 {
migration.enumerateObjects(ofType: User.className()) { old, new in
new?["fullName"] = "\(old?["firstName"] ?? "") \(old?["lastName"] ?? "")"
}
}
}
)
.realm file created in Documents by default — on iOS this falls under iCloud backup automatically. If DB large and not critical for restore, exclude via URLResourceValues.isExcludedFromBackupKey = true.
Main Pain Point — Schema Migrations
Realm requires explicit schemaVersion increment on any model change: added field, renamed, type changed — version must increase. If app already in production and user has .realm file version 2, you're shipping version 3 without migration block — crash on open.
Typical error: forgot to bump schemaVersion when adding nullable field. Realm 10+ for Kotlin SDK allows adding nullable fields without migration (auto get null), but rename, delete, type change — always need explicit migration.
Another problem — rollback. If you shipped schema version 5, then want to rollback release to version 4 — DB won't open: Realm can't downgrade migrations. Only option — deleteRealmIfMigrationNeeded in dev builds, never in production.
Write and Transactions
All Realm changes via transactions. Can't just change object field outside write block.
// Kotlin: write
realm.write {
val user = query<User>("id == $0", userId).first().find()
user?.lastSeen = Clock.System.now()
user?.isOnline = true
}
// Read with live results and subscription
val users = realm.query<User>("isActive == true")
.sort("createdAt", Sort.DESCENDING)
.asFlow()
.collect { changes ->
when (changes) {
is InitialResults -> updateUI(changes.list)
is UpdatedResults -> updateUI(changes.list)
}
}
asFlow() is reactive subscription. As soon as DB data changes, Flow emits new result. No polling, no LiveData wrapper manually. For MVVM this perfectly fits into ViewModel.
Thread Safety
Realm objects not thread-safe. Object opened in main thread can't pass to background coroutine. Each thread must open its own Realm.open(config) or use frozen() for passing snapshot.
In practice: if doing heavy write in IO dispatcher, open Realm inside same coroutine. Don't reuse instance from UI layer.
Atlas Device Sync
Realm integrates with MongoDB Atlas Device Sync — automatic bidirectional sync of local DB with cloud. For offline-capable apps this powerful option: conflict resolution, real-time updates, partition-based or flexible sync.
Connects via SyncConfiguration instead of standard RealmConfiguration, needs MongoDB Atlas account. Worth evaluating separately — full backend dependency.
Setup Realm for one platform without sync: 3–5 days. With migration strategy, reactive queries, two platforms: 1–2 weeks. Cost estimated individually.







