ewald comhaire
07/19/2023, 11:16 AMpersistable
in a flexible way (e.g. local/remote JSON file, local/remote database. After overcoming the challenges of serializing generics, instantiating <T> etc. , I came up with this working solution:
@Serializable
sealed class Persistable<T>(@Transient internal var persistableRepository: PersistableRepository<T>? = null) {
abstract fun save(): T?
abstract fun setRepository(persistableRepository: PersistableRepository<T>): T
}
@Serializable
data class SampleSettings @OptIn(ExperimentalSerializationApi::class) constructor(
@EncodeDefault var myList: MutableList<String> = mutableListOf()
) : Persistable<SampleSettings>() {
override fun save() = runBlocking { super.persistableRepository?.save(this@SampleSettings) }
override fun setRepository(persistableRepository: PersistableRepository<SampleSettings>): SampleSettings{
super.persistableRepository = persistableRepository; return this
}
}
with PersistableRepository
representing the flexible interface to load and store the members of the class, e.g.:
class PersistableFileRepository<T>(private val uri: Uri, private val serializer: KSerializer<T>, private val initialSettings: T,
private val dispatcher: CoroutineDispatcher = <http://Dispatchers.IO|Dispatchers.IO>) : PersistableRepository<T>
What is less elegant though is the fact the subclass has to override the save()
and setRepostory()
function . Ideally, it would look like:
@Serializable
data class SampleSettings @OptIn(ExperimentalSerializationApi::class) constructor(
@EncodeDefault var myList: MutableList<String> = mutableListOf()
) : Persistable<SampleSettings>()
with all persistance code abstracted/hidden in the `Persistance`library as per the C++ implementation. Can this be done in Kotlin ?