package com.example.firstapp.database.repository
|
|
import com.example.firstapp.database.dao.KeywordDao
|
import com.example.firstapp.database.entity.KeywordConfig
|
import com.example.firstapp.database.entity.KeywordEntity
|
import com.example.firstapp.database.service.ApiService
|
|
class KeywordRepository(
|
|
private val apiService: ApiService,
|
//本地缓存
|
private val keywordDao: KeywordDao
|
) {
|
suspend fun getKeywords(): List<KeywordEntity> {
|
return try {
|
// 从网络获取配置
|
val response = apiService.getKeywords()
|
if (response.code == "0") {
|
// 保存到本地数据库作为缓存
|
saveToLocal(response.data)
|
keywordDao.getAllKeywords()
|
} else {
|
// 如果接口请求失败,使用本地缓存
|
keywordDao.getAllKeywords()
|
}
|
} catch (e: Exception) {
|
e.printStackTrace() // 打印完整堆栈信息 [[3,5]]
|
// 或使用以下方式输出基本信息
|
println("网络请求异常: ${e.message}") // 打印异常消息 [[5]]
|
// 网络错误时使用本地缓存
|
keywordDao.getAllKeywords()
|
}
|
}
|
|
private suspend fun saveToLocal(keywords: List<KeywordConfig>) {
|
// keywords.map { it.toEntity() }
|
// keywordDao.insertAll(keywords)
|
val keywordEntities = keywords.map { it.toEntity() }
|
keywordDao.insertAll(keywordEntities)
|
}
|
|
}
|