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:

  1. Dependency: Include the kotlinx-coroutines-datastore library in your shared module.

  2. 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>) {
    // ...
}
  1. Data Access: Use the dataStore instance 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:

  • getAuth function returns a Flow<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 using Json.decodeFromString and wraps it in Right of Either.

    • If the key is not found, the function returns None of Option 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 and delete 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