Skip to content

Instantly share code, notes, and snippets.

@cse-ariful
Created November 14, 2022 02:53
Show Gist options
  • Save cse-ariful/921efdf7aa5fec317b8e76c3906cc3de to your computer and use it in GitHub Desktop.
Save cse-ariful/921efdf7aa5fec317b8e76c3906cc3de to your computer and use it in GitHub Desktop.
We often need to track our model class over the application lifecycle. We can do this easily using below class. No extra code needed. It's save the data in memory and retrieve from there.
import android.content.Context
import android.util.Log
import com.google.gson.Gson
import java.io.File
class ModelPersistHelper<T>(
private val context: Context,
private val gson: Gson,
private val clazz: Class<T>
) {
private val jsonPath = context.filesDir.absolutePath + "/${clazz.simpleName}.json"
suspend fun obtain(): T? {
return try {
val inputTxt = File(jsonPath).bufferedReader().use { it.readText() }
gson.fromJson(inputTxt, clazz)
}catch (ex:Exception){
return null
}
}
suspend fun save(
model: T,
onSuccess: (() -> Unit)? = null,
onError: ((Throwable) -> Unit)? = null
) {
try {
File(jsonPath).also {
it.writeBytes(gson.toJson(model).toByteArray())
}
onSuccess?.invoke()
} catch (ex: Exception) {
onError?.invoke(ex)
}
}
fun delete() {
File(jsonPath).delete()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment