So my implementation of the Kotlin Multiplatform project configuration so far is this:
which looks like this in the heirarchy:
commonMain/kotlin/config/Config.kt
commonMain/kotlin/config/ConfigProvider.kt
desktopMain/kotlin/config/DesktopConfigProvider.kt
androidMain/kotlin/config/AndroidConfigProvider.kt
our Config.kt:
class Config(val configProvider: ConfigProvider) {
var lastDepth by configProvider::lastDepth
}
our ConfigProvider.kt:
interface ConfigProvider {
var lastDepth: Double
}
our DesktopConfigProvider.kt:
import java.util.prefs.Preferences
class DesktopConfigProvider : ConfigProvider {
private val preferences = Preferences.userNodeForPackage(this::class.java)
override var lastDepth: Double
get() = preferences.getDouble("lastDepth", 0.0)
set(value) {
preferences.putDouble("lastDepth", value)
}
}
and our AndroidConfigProvider.kt:
mport android.content.Context
private const val CONFIG_KEY = "DA_MON_CONFIG"
private const val LAST_DEPTH_KEY = "LAST_DEPTH"
class AndroidConfigProvider(context: Context) : ConfigProvider {
private val sharedPreferences = context.getSharedPreferences(
CONFIG_KEY,
Context.MODE_PRIVATE
)
override var lastDepth: Double
get() = getSharedLastDepth()
set(value) {
setSharedLastDepth(value)
}
private fun setSharedLastDepth(value: Double) {
sharedPreferences?.edit()
?.putString(LAST_DEPTH_KEY, value.toString())
?.apply()
}
private fun getSharedLastDepth(): Double {
return (sharedPreferences?.getString(LAST_DEPTH_KEY, "0.0")
?.toDouble()
?: 0.0)
}
}
and here is an example test that makes a config:
import androidx.test.platform.app.InstrumentationRegistry
import io.kotest.matchers.doubles.shouldBeExactly
import org.junit.Test
class AndroidConfigProviderPersistsDepthTest {
@Test
fun configProviderPersistsDepthTest() {
val depth = 1.3
val context = InstrumentationRegistry.getInstrumentation()
.targetContext
val androidConfigProvider = AndroidConfigProvider(context)
Config(androidConfigProvider).lastDepth = depth
Config(AndroidConfigProvider(context))
.lastDepth
.shouldBeExactly(depth)
}
}
though most tests should simply make a TestConfigProvider that controls the configuration exactly as you want it for the test.
The only thing remaining is the ios and perhaps web-based projects - we will update this as we encounter those projects later.