russhwolf / multiplatform-settings

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

Add lambdas to property delegation for default values #173

Open jbruchanov opened 7 months ago

jbruchanov commented 7 months ago

currently, there is defaultValue argument as simple value like this...

var someValue: Int by settings.int("key", defaultValue = -1)

I'd be nice to have the default value deferred to the time when it's actually read, so I can use for example remote config or any other external dependency which might have some async loading with some default fallback like android/firebase remote config has.

usage would be for example this, so the remote config value would be used at the time when the someValue is actually read and not at the time when the owner instance object is created, then it gives a time potentially to remote config to sync

var someValue: Int by settings.int("key", { remoteConfig.key() } )
russhwolf commented 7 months ago

I'm wary of adding more variants to the existing API since there's already a lot of different calling conventions between nullable and non-null standard getters, operator getters, delegates, suspend/flow stuff, etc. I'll think about this, though. It might work well as a separate module. In the meantime, you can implement it yourself by doing something like

fun Settings.getInt(key: String, defaultValue: () -> Int): Int = 
    if (hasKey(key)) getInt(key, 0) else defaultValue()

For delegates you can copy the machinery of the existing delegate APIs and create analogues that call into that new function.

If you try handrollling it like that, let me know how it works for you.