How to get a LiveData list using Retrofit GET to populate a recyclerView. My code is not showing the data on screen. Is onChange() called if I'm not changing an existing list, but starting with new data first time?
MainActivity where I call the ViewModel for check data and load when set into the adapter:
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 class where I wrap the getContact function from ContactRepository:
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 class where Retrofit makes the GET request, put a LiveData> in a list inside this class and return it:
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
}
}