优化(架构与渲染): 提升流式更新性能并修复 SP 持久化阻塞主线程
1. 将 ChatViewModel 中 AI 的流式刷新频率 (STREAM_FLUSH_INTERVAL_MS) 从 50ms 调整为 150ms,以降低低端机中高频触发文本重绘(Text Layout)的沉重 CPU 负担,肉眼仍旧保持平滑。 2. 将 SharedPreferences 持久化全量对话记录(saveCacheToLocal)的操作,利用协程移动至 Dispatchers.IO 线程中,防止读写巨大 JSON 字符串时彻底堵死主线程引发应用 ANR 或冻结。
This commit is contained in:
parent
e266a4e690
commit
9ed1e31700
|
|
@ -21,7 +21,7 @@ import org.json.JSONArray
|
||||||
import org.json.JSONObject
|
import org.json.JSONObject
|
||||||
import java.util.UUID
|
import java.util.UUID
|
||||||
|
|
||||||
private const val STREAM_FLUSH_INTERVAL_MS = 50L
|
private const val STREAM_FLUSH_INTERVAL_MS = 150L
|
||||||
|
|
||||||
class ChatViewModel(application: Application) : AndroidViewModel(application) {
|
class ChatViewModel(application: Application) : AndroidViewModel(application) {
|
||||||
private val repository = AiChatRepository()
|
private val repository = AiChatRepository()
|
||||||
|
|
@ -139,34 +139,37 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun saveCacheToLocal() {
|
private fun saveCacheToLocal() {
|
||||||
try {
|
// 将数据保存放到IO线程中,防止SharedPreferences写大文本阻塞主线程卡顿
|
||||||
// 保存会话列表
|
viewModelScope.launch(kotlinx.coroutines.Dispatchers.IO) {
|
||||||
val sessionsArray = JSONArray()
|
try {
|
||||||
_sessions.value.forEach { session ->
|
// 保存会话列表
|
||||||
val obj = JSONObject()
|
val sessionsArray = JSONArray()
|
||||||
obj.put("id", session.id)
|
_sessions.value.forEach { session ->
|
||||||
obj.put("title", session.title)
|
val obj = JSONObject()
|
||||||
obj.put("timestamp", session.timestamp)
|
obj.put("id", session.id)
|
||||||
sessionsArray.put(obj)
|
obj.put("title", session.title)
|
||||||
}
|
obj.put("timestamp", session.timestamp)
|
||||||
|
sessionsArray.put(obj)
|
||||||
|
}
|
||||||
|
|
||||||
// 保存消息列表
|
// 保存消息列表
|
||||||
val messagesArray = JSONArray()
|
val messagesArray = JSONArray()
|
||||||
_messages.value.forEach { msg ->
|
_messages.value.forEach { msg ->
|
||||||
val obj = JSONObject()
|
val obj = JSONObject()
|
||||||
obj.put("id", msg.id)
|
obj.put("id", msg.id)
|
||||||
obj.put("sessionId", msg.sessionId)
|
obj.put("sessionId", msg.sessionId)
|
||||||
obj.put("role", msg.role.name)
|
obj.put("role", msg.role.name)
|
||||||
obj.put("content", msg.content)
|
obj.put("content", msg.content)
|
||||||
messagesArray.put(obj)
|
messagesArray.put(obj)
|
||||||
}
|
}
|
||||||
|
|
||||||
prefs.edit()
|
prefs.edit()
|
||||||
.putString("cache_sessions", sessionsArray.toString())
|
.putString("cache_sessions", sessionsArray.toString())
|
||||||
.putString("cache_messages", messagesArray.toString())
|
.putString("cache_messages", messagesArray.toString())
|
||||||
.apply()
|
.apply()
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
e.printStackTrace()
|
e.printStackTrace()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue