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-datastore
library in your shared module.Injection: In your KMM code, inject the
DataStore<Preferences>
instance using a dependency injection framework.
Kotlin
Data Access: Use the
dataStore
instance to access and manipulate your local data. The provided example demonstrates how to retrieve authentication information:
Kotlin
Explanation of the Example:
getAuth
function returns aFlow<RemoteData<Auth>>
.It uses
dataStore.data
to access the latest data stored in the preferences.The
map
operation transforms the retrieved data:It checks if the
authKey
exists in the preferences.If found, it decodes the stored JSON string into an
Auth
object usingJson.decodeFromString
and wraps it inRight
ofEither
.If the key is not found, the function returns
None
ofOption
representing 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
updateData
anddelete
to manage your local data.Consider using dedicated libraries like
kotlinx-serialization
for 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