DataStore
Local Data Storage with DataStore in KMM
This document explains how to implement a shared local data storage solution using DataStore for both Android and iOS.
DataStore:
DataStore is a KMM library that provides a consistent API for storing and retrieving key-value data persistently on the device. It offers advantages over platform-specific solutions by allowing you to write code once and share it across platforms.
Usage:
Dependency: Include the
kotlinx-coroutines-datastorelibrary in your shared module.Injection: In your KMM code, inject the
DataStore<Preferences>instance using a dependency injection framework.
Kotlin
class MyViewModel @Inject constructor(private val dataStore: DataStore<Preferences>) {
// ...
}Data Access: Use the
dataStoreinstance to access and manipulate your local data. The provided example demonstrates how to retrieve authentication information:
Kotlin
fun getAuth(): Flow<RemoteData<Auth>> =
dataStore.data.map { pref ->
pref[authKey]?.let {
logD(Tag.Auth.LoadAuthFromStorage, it)
Json.decodeFromString<Auth>(it).right()
}.toOption()
}Explanation of the Example:
getAuthfunction returns aFlow<RemoteData<Auth>>.It uses
dataStore.datato access the latest data stored in the preferences.The
mapoperation transforms the retrieved data:It checks if the
authKeyexists in the preferences.If found, it decodes the stored JSON string into an
Authobject usingJson.decodeFromStringand wraps it inRightofEither.If the key is not found, the function returns
NoneofOptionrepresenting missing data.
Additional Notes:
You can store various data types by converting them to JSON strings and vice versa.
You can use other DataStore operations like
updateDataanddeleteto manage your local data.Consider using dedicated libraries like
kotlinx-serializationfor more efficient object serialization and deserialization.
By using DataStore, you can achieve a unified approach for local data storage in your KMM applications, simplifying code development and platform compatibility.
Last updated