Android:存储库模式中的模型映射

问题描述 投票:0回答:1

我想从远程获取新闻并将网络响应映射到实体类以存储在存储库层的房间数据库中。我对远程和数据库使用单独的数据类

这是我正在使用的数据类......

如何添加如下所示的映射逻辑?

fun NewsRemote.toLocal() = NewsLocal(
       ..............
)

网络响应的数据类

data class NewsRemote(
    val articles: List<ArticlesItem?>? = null,
    val status: String? = null,
) {
    data class ArticlesItem(
        val publishedAt: String? = null,
        val author: String? = null,
        val urlToImage: String? = null,
        val description: String? = null,
        val source: Source? = null,
        val title: String? = null,
        val url: String? = null,
        val content: String? = null
    ) {
        data class Source(
            val name: String? = null,
            val id: String? = null
        )
    }
}

数据库的数据类

@Entity(tableName = "news")
data class NewsLocal(
    @PrimaryKey
    var id: Int = Random().nextInt(),
    var publishedAt: String? = null,
    var author: String? = null,
    var urlToImage: String? = null,
    var description: String? = null,
    var source: Source? = null,
    var title: String? = null,
    var url: String? = null,
    var content: String? = null
)

我正在尝试添加如下内容,但不确定如何准确映射

fun NewsRemote.toLocal() = NewsLocal(
       ..............
)
android kotlin repository-pattern android-architecture-components android-mvvm
1个回答
0
投票

标记实体或 POJO 的字段,以允许在 SQL 查询中直接引用嵌套字段(即带注释的字段类的字段)。

如果容器是实体,这些子字段将是实体数据库表中的列。

源类新的嵌入实体。

您的实体

@Entity(tableName = "news")
data class NewsLocal(
    @PrimaryKey(autoGenerate = true) 
    val id: Int,
    val publishedAt: String?,
    val author: String?,
    val urlToImage: String?,
    val description: String?,
    @Embedded 
    val source: Source?,
    val title: String?,
    val url: String?,
    val content: String?
)

@Entity(tableName = "source")
data class Source(
    @PrimaryKey(autoGenerate = true)
    val id: String,
    val name: String
)

映射

fun NewsRemote.ArticlesItem.toLocalNews(): NewsLocal {
   val sourceObj = Source(
        id = this.source?.id ?: "",
        name = this.source?.name ?: ""
    )

    return NewsLocal(
        id = 0,
        publishedAt = this.publishedAt,
        author = this.author,
        urlToImage = this.urlToImage,
        description = this.description,
        source = sourceObj,
        title = this.title,
        url = this.url,
        content = this.content
    )
}

fun NewsRemote.toLocalNewsList(): List<NewsLocal> {
    
   val newsLocalList: MutableList<NewsLocal> = mutableListOf()
   this.articles?.forEach { articleItem ->
        
        if (articleItem != null) {
            val localNews = articleItem.toLocalNews()
            newsLocalList.add(localNews)
        }
    }
    return newsLocalList
}
© www.soinside.com 2019 - 2024. All rights reserved.