/** * 第 10 章 · 实战项目 — 数据持久化(JSON 文件) * * 用 kotlinx.serialization 做 JSON,用协程把 IO 切到 IO 线程池。 */ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import java.io.File object Repository { private val dataFile = File(System.getProperty("user.home"), ".todo/data.json") private val json = Json { prettyPrint = true ignoreUnknownKeys = true encodeDefaults = true } suspend fun load(): MutableList = withContext(Dispatchers.IO) { if (!dataFile.exists()) return@withContext mutableListOf() runCatching { json.decodeFromString>(dataFile.readText()).toMutableList() }.getOrElse { e -> System.err.println("⚠️ 数据文件损坏,使用空列表: ${e.message}") mutableListOf() } } suspend fun save(todos: List) = withContext(Dispatchers.IO) { dataFile.parentFile?.mkdirs() dataFile.writeText(json.encodeToString(todos)) } fun nextId(todos: List): Int = (todos.maxOfOrNull { it.id } ?: 0) + 1 }