Hi. In my ViewModel, I need to use the same case m...
# android
e
Hi. In my ViewModel, I need to use the same case multiple times with different arguments (keyword). I have something like this, but I don't know how efficient it is. If not, would you guys recommend some alternatives? The use case returns a list of items which is gonna be different for every call. Thanks!
Copy code
init {
        getMainNews()
    }

    fun getMainNews() {
        combine(
            getAllTopNewsUseCase(pageSize = "10"),
            getNewsByKeywordUseCase(keyword = keywordOne, pageSize = "15"),
            getNewsByKeywordUseCase(keyword = keywordTwo, pageSize = "15"),
            getNewsByKeywordUseCase(keyword = keywordThree, pageSize = "15"),
            getNewsByKeywordUseCase(keyword = keywordFour, pageSize = "15"),
            localState
        ) { topNews, newsByKeyword1, newsByKeyword2, newsByKeyword3, newsByKeyword4, localState ->

        }.catch {

        }.launchIn(viewModelScope)
    }
a
Would changing
getNewsByKeywordUseCase
to get a list of keywords help?
getNewsByKeywordUseCase()
code would be required to analyse that.
e
@Abhimanyu For every keyword I'll get a list of news. For example: getNewsByKeywordUseCase("water") - Return a list of news regarding water. getNewsByKeywordUseCase("flowers") - Return a list of news regarding flowers.
GetNewsByKeywordUseCase
:
Copy code
class GetNewsByKeywordUseCase @Inject constructor(
    private val repository: NewsRepository
) {
    operator fun invoke(keyword: String, pageSize: String): Flow<List<NewsItem>> = flow {
        val news = repository.getNewsByKeyword(keyword, pageSize).articles
        emit(news)
    }
}
API method:
Copy code
@GET("everything?" +
            "apiKey=${BuildConfig.NEWS_API_KEY}&" +
            "searchIn=title&" +
            "language=en&" +
            "sortBy=publishedAt")
    suspend fun getNewsByKeyword(
        @Query("q") keyword: String,
        @Query("pageSize") pageSize: String
    ): NewsResponse
a
Is the API called for every change 🤔 . 1. Are there always 4 keywords required in the combine? 2. Can we change this to suspend and call the API where required instead of making 4 API calls for every keyword change as this is a one shot operation?
m
@Enrique Ajin, please also reconsider how you're dealing with init, as it's an anti-pattern. Check out this Medium post for more details on how to better model them.