KMP Compose Multiplatform DataStore Alternative

336 Views Asked by At

I've been working in my KMP Project (Android-Desktop), but it seems KMP has no supports for Desktop (yet?).

The problem I faced is on this code on androidMain in sample github repo:

fun getDataStore(context: Context): DataStore<Preferences> = getDataStore(
    producePath = { context.filesDir.resolve(dataStoreFileName).absolutePath }
)

How can I replace the the directory or path for Desktop?

And if possible, I want to know other DataStore / SharedPreference-like libraries and their use example for KMP

1

There are 1 best solutions below

0
On BEST ANSWER

Nevermind, I have found how to do DataStore/SharedPref thing in KMP.

Currently, I'm using Multiplatform Settings

Here's the example:

Shared:

expect class MultiplatformLocalUserWrapper {
    expect fun createLocalUserPref(): ObservableSettings
}

Android:

object ContextUtils {

    private var kmpAppContext: Context? = null

    val context
        get() = kmpAppContext
            ?: error("Android context has not been set. Please call setContext in your Application's onCreate.")

    fun setContext(context: Context) {
        kmpAppContext = context
    }
}

actual class MultiplatformLocalUserWrapper {

    val context = ContextUtils.context

    actual fun createLocalUserPref(): ObservableSettings {
        val sharedPref =
            context.getSharedPreferences("user_local", Context.MODE_PRIVATE)
        return SharedPreferencesSettings(sharedPref)
    }
}

Desktop (Use JVM):

actual class MultiplatformLocalUserWrapper {
    actual fun createLocalUserPref(): ObservableSettings {
        val preferences = Preferences.userRoot()
        return PreferencesSettings(preferences)
    }
}

If you wanna go for specific platform for ObservableSettings see this link