我正在从新闻api获得数据响应,我需要通过根据来源对数据进行分组在回收器视图中显示这些数据。
基本上我正在获取ArticalDto列表,并且我希望将此列表转换为List,因为我需要按来源对数据进行分组并在回收视图中以多个视图显示。我当时正在考虑使用GroupBy或Map来实现,但是没有确切的方法。这是我编写的用于从网络获取数据的代码。
class ContentListViewModel : BaseViewModel() {
internal val result = MutableLiveData<Result<ArticlesDto>>()
/**
* Fetches news from sources.
* You do not need to understand this implementation in order to complete the assignment.
* All the updates (response) are posted to the [result] liveData.
*/
fun fetchNews(params: ContentParams = ContentParams()) {
NewsApiRepository(apiKey = apiKey).getEverything(
q = params.q,
sources = params.sources,
domains = params.domains,
language = params.language,
sortBy = params.sortBy,
pageSize = params.pageSize,
page = params.page
)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.toFlowable()
.subscribe(
{ result.value = Result.success(it) },
{
Log.e("Error", it.cause?.message ?: "")
result.value = Result.failure(it)
}
).disposeOnClear()
}
}
有人可以建议我如何使用rxjava实现这一目标吗?我可以先将列表转换为Hashmap,然后再将其转换为列表,但要为此使用rxjava。
答案 0 :(得分:0)
创建新的api响应pojo类。 然后在下面的代码中使用。.
var categoryResult: MutableLiveData<List<CategoryModel>> = MutableLiveData()
api调用..
fun getCategoryData(storeId: String) {
if (ConnectivityUtils.isNetworkAvailable(getApplication())) {
showProgressDialog.postValue(true)
storeData = storeId
launch {
appApiInterface
.getCategories(storeId)
.with(schedulerProvider)
.subscribe(
{ result ->
showProgressDialog.postValue(false)
if (result.categories != null)
categoryResult.postValue(result.categories)
else
showNoData()
},
{ e ->
showProgressDialog.postValue(false)
interFragmentInterface?.showDialog(e.getErrorMessage(getApplication()))
}
)
}
} else {
interFragmentInterface!!.showDialog(getApplication<Application>().getString(R.string.error_message_network))
}
}
之后在活动中或使用片段观察器。
viewModel.categoryResult.observe(this, Observer { it ->
// here set api list of data into adapter class insert method.
// here set your adapter code.
})
使用viewModel更容易。