If I have the following class, how can I save a list of it with Proto DataStore?
data class Tag(
val id: int,
val name: String
)
All guides that I saw were teaching how to save only a single object. Is it possible to have a list of it?
If I have the following class, how can I save a list of it with Proto DataStore?
data class Tag(
val id: int,
val name: String
)
All guides that I saw were teaching how to save only a single object. Is it possible to have a list of it?
You should consider storing list of content in Room, Even proto-datastore isnt a proper solution to store complex stuff,
If you still want then, I will suggest you to restrict the data stored to 10-15 items
to the code --->
list
type for Javamessage Student {
string id = 1;
string name = 2;
}
message ClassRoom {
string teacher = 1;
repeated Student students = 2; // repeated => list
}
dataStore.updateData { store ->
store.toBuilder()
.clearStudents() // clear previous list
.setAllStudents(students)// add the new list
.build()
}
if you want example checkout my sample app, read the data/domain layer https://github.com/ch8n/Jetpack-compose-thatsMine
You can encode your class object into json string by the help of kotlinx json library and store that string into datastore preference like below ->
@Serializable
data class EmployeeCorporateInfo(
@SerialName("companyName")
val companyName: String,
@SerialName("employeeInfo")
val employeeInfo: EmployeeInfo,
@SerialName("firstName")
val firstName: String,
@SerialName("id")
val id: String,
@SerialName("lastName")
val lastName: String,
@SerialName("middleName")
val middleName: String
)
@Serializable
data class EmployeeCorporates(val corporates:List<EmployeeCorporateInfo>)
Encode into JSON:
val employeeCorporates = EmployeeCorporates(emptyList())
val rawCorporate:String = Json.encodeToString(employeeCorporates ))
Store rawCorporate
into preference data store. After whenever you need that get from preference data store and decode that string into our class object.
val employeeCorporates = Json.decodeFromString<EmployeeCorporate(rawCorporate)
© 2022 - 2025 — McMap. All rights reserved.