Android Kotlin Coroutines通过链接的网络请求获取数据

时间:2019-09-09 03:22:32

标签: kotlin android-livedata kotlin-coroutines mediator android-mvvm

Q)如何使用协程使用链接的网络请求来更新每个项目的viewModel?

我正在尝试从api中获取一些对象,但是api需要进行初始调用以获取objectIds数组,然后使用包括objectId在内的单个调用来获取每个对象。我当前的实现链接了所有网络调用,但是仅在整个循环完成后才返回。

例如:

@GET ... api / topItems返回[1111,2245,5456,...]

@GET ... api / item?id = 1111

@GET ... api / item?id = 2245

以此类推。

我的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)
}

}

0 个答案:

没有答案