Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mapping to Flow and using it as a List<Item>

Im using retrofit and fetching data from news api.
I wanted to use flows so I do this in repository:

  fun getTopArticles(): Flow<List<Article>> {
        return flow {
            val topArticles = apiService.getTopHeadlinesArticles().articles
                .map { article ->
                    Article(
                        title = article.title,
                        content = article.content
                    )
                }
            emit(topArticles)
        }.flowOn(Dispatchers.IO)
    }

ViewModel:

private val _observeTopArticles = MutableStateFlow(emptyList<Article>())
    val observeTopArticles = _observeTopArticles.asStateFlow()

  init {
        viewModelScope.launch {
            articleRepository.getTopArticles()
                .collect{
                    _observeTopArticles.value = it
                }
        }
    }

Activity:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

lifecycleScope.launch{
    viewModel.observeTopArticles.collect{
        if (it.isNotEmpty()){
        }
    }
}

I wanted to get something like this:

[Article(I know something, some content)] etc.

But I get this:

[android.newz.domain.Article@5f612be, android.newz.domain.Article@700f1f]

I want to use it in RecyclerView.

>Solution :

I think your Flow code is fine. Looks like the problem is that Article doesn’t have a toString() implementation, so you’re just seeing the default String representation. Try making Article into a data class.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading