如何将Flow<List<T>>转换为Flow<List<R>>?

huangapple go评论54阅读模式
英文:

How to convert Flow<List<T>> to Flow<List<R>>?

问题

I'm building a repository to retrieve data from a Room database. The Room dao returns a Flow<List<ObjectDto>>. However, I need to convert this to Flow<List<Object>. What is the right way to do this?

This is the solution I've come up with. I have a mapper extension ObjectDto.toObject(). However, this solution doesn't seem right to me. I have no experience with flows, but collecting and emitting again can't be correct, right?

    override fun getObjects(): Flow<List<Object>> {
        return flow {
            objectDao.getObjects().collect { objectDtoList ->
                val objects = objectDtoList.map { it.toObject() }
                emit(objects) }
        }
    }

I also found several operators to use on flows without collecting them, but while some of them are able to change the type, I'm not sure how to change the type of a list using these operators.

英文:

I'm building a repository to retrieve data from a Room database. The Room dao returns a Flow&lt;List&lt;ObjectDto&gt;&gt;. However, I need to convert this to Flow&lt;List&lt;Object&gt;&gt;. What is the right way to do this?

This is the solution I've come up with. I have a mapper extension ObjectDto.toObject(). However, this solution doesn't seem right to me. I have no experience with flows, but collecting and emitting again can't be correct, right?

    override fun getObjects(): Flow&lt;List&lt;Object&gt;&gt; {
        return flow {
            objectDao.getObjects().collect { objectDtoList -&gt;
                val objects = objectDtoList.map { it.toObject() }
                emit(objects) }
        }
    }

I also found several operators to use on flows without collecting them, but while some of them are able to change the type, I'm not sure how to change the type of a list using these operators.

答案1

得分: 3

我认为Flow.map是你在寻找的

override fun getObjects(): Flow<List<Object>> =
    objectDao.getObjects().map { objectDtoList ->
         objectDtoList.map { it.toObject() }
    }
}
英文:

I think Flow.map is what you're looking for

override fun getObjects(): Flow&lt;List&lt;Object&gt;&gt; =
    objectDao.getObjects().map { objectDtoList -&gt;
         objectDtoList.map { it.toObject() }
    }
}

huangapple
  • 本文由 发表于 2023年2月16日 05:10:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75465464.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定