如何使用翻新GET获取LiveData列表以填充recyclerView。我的代码未在屏幕上显示数据。如果我不更改现有列表,而是第一次从新数据开始,是否调用onChange()?
MainActivity,我在其中调用ViewModel来检查数据并在设置到适配器中时加载:
var mContactViewModel = ViewModelProviders.of(this).get(ContactViewModel::class.java)
mContactViewModel.getContacts(this)?.observe(this, object : Observer<List<Contact>> {
override fun onChanged(contactsList: List<Contact>?) {
loading_contacts_list.visibility = View.GONE
if(contactsList!!.isNotEmpty()){
rv_users.adapter = ContactsAdapter(contactsList, onContactClick, context)
} else {
//TODO throw exception
println("list of contacts returned empty")
}
}
})
ContactViewModel类,其中包装了ContactRepository的getContact函数:
class ContactViewModel(application: Application) : AndroidViewModel(application) {
private val mRepository: ContactRepository
init {
mRepository = ContactRepository()
}
fun getContacts(context: Context) : LiveData<List<Contact>>? {
return mRepository.getContacts(context)
}
}
ContactRepository类,其中Retrofit发出GET请求,将LiveData>放在此类的列表中并返回:
class ContactRepository {
var allContacts: LiveData<List<Contact>>? = null
var call: Call<LiveData<List<Contact>>>
init {
var requestService: RequestService = RetrofitClient().getClient(MY_URL)!!.create(RequestService::class.java)
call = requestService.getContacts()
}
fun getContacts(context: Context) : LiveData<List<Contact>>? {
call.enqueue(object : Callback<LiveData<List<Contact>>> {
override fun onFailure(call: Call<LiveData<List<Contact>>>, t: Throwable) {
Log.e("Tag onfailure", "retrofit on failure", t)
}
override fun onResponse(call: Call<LiveData<List<Contact>>>, response: Response<LiveData<List<Contact>>>) {
if(response.isSuccessful)
allContacts = response.body()
}
})
return allContacts
}
}