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

Time:10-19

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:

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.

CodePudding user response:

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.

  • Related