1

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

0

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.