英文:
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<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.
答案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<List<Object>> =
objectDao.getObjects().map { objectDtoList ->
objectDtoList.map { it.toObject() }
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论