-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJsonViewModelEncoder.kt
More file actions
35 lines (30 loc) · 1.05 KB
/
JsonViewModelEncoder.kt
File metadata and controls
35 lines (30 loc) · 1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.dmm.eikaiwa.viewmodels
import kotlinx.serialization.KSerializer
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.buildJsonObject
class JsonViewModelEncoder<T>(
private val parser: Json,
private val serializer: KSerializer<T>,
private val viewModel: T
) {
private val referenceCache: ViewModelReferenceCache
get() {
val contextSerializer = parser.serializersModule.getContextual(
ViewModelContext::class
) as? ViewModelContextSerializer ?: throw ReferenceCacheNotFoundException()
return contextSerializer.referenceCache
}
fun encode(): String {
val data = parser.encodeToJsonElement(
serializer,
value = viewModel
)
val references = referenceCache.encoded
val jsonObject = buildJsonObject {
put("data", data)
put("references", JsonObject(references))
}
return parser.encodeToString(jsonObject)
}
}