russhwolf / multiplatform-settings

A Kotlin Multiplatform library for saving simple key-value data
Apache License 2.0
1.69k stars 67 forks source link

Settings.stringSet(key: String? = null, defaultValue: Set<String> = emptySet(), separator = ",") #67

Closed vanniktech closed 3 years ago

vanniktech commented 3 years ago

Implementation could look something like this:

internal class SettingsDelegateSetString(
  private val settings: Settings,
  private val key: String,
  private val default: Set<String>,
  private val separator: String
) {
  operator fun getValue(thisRef: Any?, prop: KProperty<*>) =
    settings.getStringOrNull(key)
      ?.split(separator)
      ?.toSet()
      ?: default

  operator fun setValue(thisRef: Any?, prop: KProperty<*>, value: Set<String>) =
    settings.putString(key, value.joinToString(separator = separator))
}

Do you think that's a good fit?

russhwolf commented 3 years ago

Is it useful? I've never found much need for the StringSet APIs in SharedPreferences.

The solution I find more interesting for non-primitive data is the kotlinx.serialization integration I have prototyped in #36. This would generalize much better to other simple datatypes without needing to special-case anything. Looking to probably release that in the near future as part of 0.7. Do you think that will fit your use-case? You'd be able to do something like

val stringSet by settings.serializationDelegate(SetSerializer(String.serializer()), "key")
vanniktech commented 3 years ago

Yup that would work too.

russhwolf commented 3 years ago

The serialization integration is now released in 0.7 so I'm closing this.