Q) How can I update my viewModel per item using chained network requests using coroutines?
I'm trying to fetch some objects from an api, but the api requires an initial call to fetch an array of objectIds, and then each object is fetched with an individual call including the objectId. My current implementation chains all the network calls, but only returns when the entire loop has completed.
for example:
@GET ...api/topItems returns [ 1111, 2245, 5456, ... ]
@GET ...api/item?id=1111
@GET ...api/item?id=2245
and so on.
My ViewModel
class FeedItemListViewModel(
private val retrieveItemsFromApiUseCase: RetrieveItemsFromApiUseCase
) : ViewModel() {
private val _feedItemsFromApi = MutableLiveData<List<FeedItem>>()
val feedItemsFromApi: LiveData<List<FeedItem>>
get() = _feedItemsFromApi
fun retrieveFeedItemsFromApi() {
viewModelScope.launch {
val result = retrieveItemsFromApiUseCase.invoke("topItems")
when (result) {
is NetworkResult.Success -> {
_feedItemsFromApi.postValue(result.data)
}
is NetworkResult.Error -> Timber.d("no feed items from api ${result.exception}")
}
}
}
}
RetrieveItemsFromApiUseCase
class RetrieveItemsFromApiUseCase(private val repository: InMemoryRepository) {
suspend operator fun invoke(feedType: String): NetworkResult<List<FeedItem>> = withContext(Dispatchers.IO) {
val itemList: MutableList<FeedItem> = mutableListOf()
val result = repository.fetchTopItems()
when (result) {
is NetworkResult.Success -> {
itemList.addAll(result.data)
for (i in 0..9) {
val emptyItem = result.data[i]
val response = repository.fetchItem(emptyItem.id)
when (response) {
is NetworkResult.Success -> {
val item = response.data
emptyItem.setProperties(item)
}
}
}
}
is NetworkResult.Error -> return@withContext result
}
return@withContext NetworkResult.Success(itemList)
}
}