Hi guys, I am having difficulty mapping a List of ...
# android
s
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
I believe it depends on what you want to present. You can make the PostResponse a field of your UiPostResponse. Eg:
Copy code
UiPostResponse1(val postResponse: PostResponse) : IPostResponsePresenter
UiPostResponse2(val postResponse: PostResponse) : IPostResponsePresenter
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
I tried the direct mapping but direct mapping dosen't work with Lists eg. List<PostResponse>
d
The Ui data should contain just the values you want to use in the ui and not the entire post response
p
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.
s
Thanks alot, It works.
👍 1