Setting up MMKV Storage in Mobile Application
SharedPreferences on Android and UserDefaults on iOS are synchronous read-write operations for small values, but with non-obvious overhead. SharedPreferences.apply() is asynchronous while commit() blocks the main thread. UserDefaults.synchronize() is deprecated, but usage patterns remain. MMKV from Tencent solves this via mmap: write to memory, OS flushes to disk in background — no explicit flush, no blocking.
Connection
// Android: build.gradle
implementation("com.tencent:mmkv:1.3.5")
// Application.onCreate()
MMKV.initialize(this)
// iOS: Package.swift or CocoaPods
// pod 'MMKV', '~> 1.3'
// or SPM: https://github.com/Tencent/MMKV
import MMKV
// AppDelegate.application(_:didFinishLaunchingWithOptions:)
MMKV.initialize(rootDir: nil)
Initialize once at startup, then MMKV.defaultMMKV() is available everywhere without singletons.
Usage
val kv = MMKV.defaultMMKV()
// Write
kv.encode("userId", userId)
kv.encode("authToken", token)
kv.encode("lastSyncTimestamp", System.currentTimeMillis())
kv.encode("featureFlags", flagsSet)
// Read
val token = kv.decodeString("authToken") ?: ""
val lastSync = kv.decodeLong("lastSyncTimestamp", defaultValue = 0L)
Typed methods for all primitives: encodeInt, encodeBool, encodeFloat, encodeBytes — for serialized Protobuf/JSON objects.
Encryption
MMKV supports file-level AES-128 encryption:
val encryptedKV = MMKV.mmkvWithID("secure-storage", MMKV.SINGLE_PROCESS_MODE, "your-crypto-key")
Never store the encryption key in code — retrieve it from Android Keystore or iOS Secure Enclave:
let key = try KeychainManager.getOrCreateEncryptionKey(identifier: "mmkv-key")
let secureKV = MMKV(mmapID: "secure", cryptKey: key.data)
When MMKV, When Something Else
MMKV is not a database replacement. For key-value pairs with fast access (settings, tokens, small value cache), it's an excellent choice. For structured data with queries, use Room or SQLite.
SharedPreferences to MMKV migration on Android takes an hour — API is nearly identical. Noticeable result: StrictMode warnings about disk read in main thread disappear when SharedPreferences is first read.
MMKV setup with encryption and migration from SharedPreferences/UserDefaults: 1–2 days. Cost calculated individually.







