Good morning all. I'm looking to use DataStore in...
# multiplatform
m
Good morning all. I'm looking to use DataStore in a KMP project. I've got a data class defined for what i want to represent (it will just be a list of a this data class):
Copy code
data class StringTableKey(
    val name: String,
    val languageCode: String,
    val countryCode: String
)

interface StringTable {
    fun asMap(): Map<StringTableKey, String>
}
I want to define a DataStore for StringTable. However, it seems that the "Serializer" interface exists only in the android artifact. If that's the case, how am i supposed to define serialization for the iOS side of things?
v
Yeah. the
androidx.datastore.core.Serializer
does not exist in common code. If you really want to do it this way - you should expose your store as an expect / actual implementation. The actual implementation for Android would use the Serializer, On iOS - use a file solution (`NSDocumentDirectory`and so on), On JS - use localStorage. Or, you just use
DataStore<Preferences>
and save the
Map<StringTableKey, String>
with a
forEach
, with no serailization. Though deserializing will be a bit more problematic. EDIT: You could just serialize the key using JSON and save it as the preference key
m
Yeah, i've seen this example in the documentation:
Copy code
fun createDataStore(): DataStore<Preferences> = createDataStore(
    producePath = {
        val documentDirectory: NSURL? = NSFileManager.defaultManager.URLForDirectory(
            directory = NSDocumentDirectory,
            inDomain = NSUserDomainMask,
            appropriateForURL = null,
            create = false,
            error = null,
        )
        requireNotNull(documentDirectory).path + "/$dataStoreFileName"
    }
)
And so i'd have to wrap the calls to to this to generate the keys and values from my data structures, and likewise when it reconstitutes.
That seams reasonable. I can create implementations of my interface backed by a Preferences instance, and provide a transform for the flow you get from the datastore
Thanks @Vidmantas Kerbelis for the advice:
Copy code
fun Preferences.asStringTable(): StringTable =
    PreferencesStringTable(this)

fun Flow<Preferences>.toStringTableFlow(): Flow<StringTable> =
    map {
        it.asStringTable()
    }
I think this will work well for me as 99% of the app only wants the immutable version and won't be pushing strings.
kodee happy 1