cloudroam
2025-02-25 0fce8fea0b83afb02b5d8780160787e87b8ceedb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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.status == 1) {
                // 保存到本地数据库作为缓存
                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)
    }
 
}