git.iko.soy/opencode-android
on 3e723a1 help sign in
40 lines 1.4 kB history raw
1package soy.iko.opencode.data.repo
3import android.content.Context
4import kotlinx.coroutines.CoroutineScope
5import kotlinx.coroutines.launch
7/**
8 * Persists the in-progress message draft for each session so it survives
9 * back-navigation and process death. Backed by SharedPreferences because the
10 * UI needs the initial value synchronously and drafts are low-stakes data.
11 *
12 * The prefs file is loaded on a background thread at construction time so the
13 * first [get] call on the main thread doesn't trigger a synchronous disk read.
14 */
15class DraftStore(context: Context, scope: CoroutineScope) {
17 private val appContext = context.applicationContext
18 private val prefs by lazy {
19 appContext.getSharedPreferences("drafts", Context.MODE_PRIVATE)
20 }
22 init {
23 // Eagerly load the prefs file on a background thread so the first main-thread
24 // get() doesn't block on disk I/O. The lazy delegate ensures the same instance.
25 scope.launch { prefs.all }
26 }
28 fun get(sessionId: String): String = prefs.getString(sessionId, "").orEmpty()
30 fun set(sessionId: String, text: String) {
31 prefs.edit().apply {
32 if (text.isBlank()) remove(sessionId) else putString(sessionId, text)
33 }.apply()
34 }
36 /** Remove the draft for a session (call on session deletion to avoid orphaned entries). */
37 fun remove(sessionId: String) {
38 prefs.edit().remove(sessionId).apply()
39 }