@@ -2,6 +2,7 @@ package li.songe.gkd.store
22
33import kotlinx.coroutines.CoroutineScope
44import kotlinx.coroutines.Dispatchers
5+ import kotlinx.coroutines.ExperimentalForInheritanceCoroutinesApi
56import kotlinx.coroutines.flow.MutableStateFlow
67import kotlinx.coroutines.flow.conflate
78import kotlinx.coroutines.flow.debounce
@@ -41,16 +42,29 @@ private fun writeStoreText(file: File, text: String) {
4142 )
4243}
4344
45+ @OptIn(ExperimentalForInheritanceCoroutinesApi ::class )
46+ class MutableStoreStateFlow <T >(
47+ val filename : String ,
48+ val decode : (String? ) -> T ,
49+ val encode : (T ) -> String ,
50+ private val stateFlow : MutableStateFlow <T >,
51+ ) : MutableStateFlow<T> by stateFlow {
52+ fun encodeSelf (): String = encode(value)
53+ fun updateByDecode (text : String? ) {
54+ value = decode(text)
55+ }
56+ }
57+
4458fun <T > createTextFlow (
4559 key : String ,
4660 decode : (String? ) -> T ,
4761 encode : (T ) -> String ,
4862 private : Boolean = false,
4963 scope : CoroutineScope = appScope,
5064 debounceMillis : Long = 0,
51- ): MutableStateFlow <T > {
52- val name = if (key.contains(' .' )) key else " $key .txt"
53- val file = (if (private) privateStoreFolder else storeFolder).resolve(name )
65+ ): MutableStoreStateFlow <T > {
66+ val filename = if (key.contains(' .' )) key else " $key .txt"
67+ val file = (if (private) privateStoreFolder else storeFolder).resolve(filename )
5468 val initText = readStoreText(file)
5569 val initValue = decode(initText)
5670 val stateFlow = MutableStateFlow (initValue)
@@ -61,7 +75,12 @@ fun <T> createTextFlow(
6175 }
6276 }
6377 }
64- return stateFlow
78+ return MutableStoreStateFlow (
79+ filename = filename,
80+ decode = decode,
81+ encode = encode,
82+ stateFlow = stateFlow,
83+ )
6584}
6685
6786inline fun <reified T > createAnyFlow (
@@ -71,7 +90,7 @@ inline fun <reified T> createAnyFlow(
7190 private : Boolean = false,
7291 scope : CoroutineScope = appScope,
7392 debounceMillis : Long = 0,
74- ): MutableStateFlow <T > {
93+ ): MutableStoreStateFlow <T > {
7594 return createTextFlow(
7695 key = " $key .json" ,
7796 decode = {
0 commit comments