Hi guys, I am having difficulty mapping a List of Posts Flow exposed form the Repository to UI data in the viewmodel
Copy code
//Repository
data class PostResponse(
val body: String,
val title: String,
val id: Int,
val userId: Int
)
class NewsRepository @Inject constructor(private val newsRemoteDataSource: NewsRemoteDataSource ) {
val fetchLatestNews : Flow<List<PostResponse>> = newsRemoteDataSource.fatchLatestNews
//ViewModel
data class UiPostResponse(
val post: PostResponse,
val message: String = "message"
)
class UiViewModel @Inject constructor(private val newsRepository: NewsRepository): ViewModel() {
private val data : Flow<UiPostResponse> = newsRepository.fetchLatestNews.map { post->
UiPostResponse(
//
)
}
Please what would be the best way to map a list of flow data to useful UI data in the viewmodel?
p
Pablichjenkov
11/04/2022, 8:08 PM
I believe it depends on what you want to present. You can make the PostResponse a field of your UiPostResponse. Eg:
and have as many UiPostResponse presenters as you UI needs. It is up to your App specs.
If you want to fully decouple you UI/Data domain from your API domain then you can do direct mapping. eg:
UiPostResponse1.title = PostResponse.title
and so on
s
Solomon Tolu Samuel
11/04/2022, 8:15 PM
I tried the direct mapping but direct mapping dosen't work with Lists eg. List<PostResponse>
d
Daniel
11/04/2022, 10:43 PM
The Ui data should contain just the values you want to use in the ui and not the entire post response
p
Pablichjenkov
11/04/2022, 10:49 PM
Oh I think I understand your question better. You can use something like below
Copy code
private val uiMappedData : Flow<List<UiPostResponse>> = newsRepository.fetchLatestNews.map { postList->
postList.map { postResponse ->// This map refers to the List<T>.map and not Flow<T>.map
// Do direct mapping here
UiPostResponse().apply {title = postResponse.title}
}
}
As Ezike mentioned, map only what you need, is cleaner.