matt tighe
07/10/2019, 5:35 PMinterface PreferenceAccessor {
val fileName: String
val context: Context
val prefs: SharedPreferences
get() = context.getSharedPreferences(fileName, Context.MODE_PRIVATE)
}
class PrefAccessorImpl(ctx: Context): PreferenceAccessor {
override val fileName: String
get() = "somePrefFileName"
override val context: Context
get() = ctx
}
What I’m looking for is a way to define a bunch of shared preference implementations with different file names, but save on the boilerplate of using context to initialize them. i’d also like to avoid having Context
objects actually injectedflorent
07/10/2019, 6:04 PMEric Martori
07/10/2019, 6:10 PMfun Context.namePreferences() = this.getSharedPreferences("name", Context.MODE_PRIVATE)
Context
aroundmatt tighe
07/10/2019, 6:31 PMclass PrefAccessor1(ctx: Context) {
private val cacheFileName1 = "1"
private val prefs = ctx.getSharedPreferences(cacheFileName1, Context.MODE_PRIVATE)
// Business logic specific to this section of the cache
}
class PrefAccessor2(ctx: Context) {
private val cacheFileName1 = "2"
private val prefs = ctx.getSharedPreferences(cacheFileName2, Context.MODE_PRIVATE)
// Business logic specific to this section of the cache
}
Context
in them, as they could be long-livingIanmedeiros
07/10/2019, 9:18 PMAl Warren
07/10/2019, 11:50 PMPaulius Ruminas
07/11/2019, 6:05 AMEric Martori
07/11/2019, 10:26 AMinterface Cache {
fun cache(item: Any) //this would depend on how you will use them, maybe use generics, etc
fun getCached(key: Any) //this would depend on how you will use them, maybe use generics, etc
}
abstract class NamedPreferencesCache(name: String, ctx: Context) : Cache {
protected val preferences = ctx.getSharedPreferences(name, Context.MODE_PRIVATE)
//common caching logic
}
class FirstPreferencesCache(ctx: Context) : NamedPreferencesCache("first", ctx) {
//specific caching logic
}
matt tighe
07/11/2019, 7:21 PM