Home > Software engineering >  How can i work with flow inside repository android?
How can i work with flow inside repository android?

Time:04-06

I wrote code which works fine without kotlin flow, but i want to try kotlin flow and when i used it inside repository but somehow it is not even entering inside i could not find any solution since it is not throwing any error, it is just not entering inside function and i think it is because of flow collector. It is coming till repository but for repo it is not entering.

class NewsRepositoryImpl(private val newsService: NewsService) : NewsRepository {
override suspend fun getNews(search: String): Flow<ResultWrapper<List<Article>>> = flow {
    emit(ResultWrapper.Loading)
    try {
        val news = newsService.getNews(search, BuildConfig.API_KEY)
        emit(ResultWrapper.Success(news.articles.map { it.toArticle() }))
    } catch (e: Exception) {
        emit(ResultWrapper.Error(e.message))
    }   
  }
}

CodePudding user response:

Using flow builder you create a cold stream of data. The code inside it is executed only when the flow is being collected, i.e. terminal operators invoked, for example collect, collectLatest, first... .

coroutineScope.launch {
    newsRepository.getNews("news").collectLatest { result ->
        // use result
    }
}
  • Related