所有正常工作的API请求都返回响应,但是活动观察器仅在第一次触发时才使用空值,并且当来自请求观察器的响应未看到更改时。
活动:
viewModel.jobQuestions.observe(this, Observer { list ->
list?.let {
jobQuestionsRv.apply {
setAdapterData(list)
}
}
})
ViewModel:
class JobQuestionsViewModel @Inject constructor(private val repository: Repository) : ViewModel() {
private val _jobQuestions = MutableLiveData<List<QuestionModel>>()
val jobQuestions: LiveData<List<QuestionModel>> = _jobQuestions
init {
_jobQuestions.postValue(repository.getQuestions())
}
}
存储库:
override fun getQuestions(): List<QuestionModel> {
var questionsList = ArrayList<QuestionModel>()
apiRequests?.questions()?.enqueue(object : retrofit2.Callback<List<QuestionModel>> {
override fun onResponse(
call: Call<List<QuestionModel>>?,
response: Response<List<QuestionModel>>
) {
response.body()?.let {
questionsList.addAll(response.body())
}
}
override fun onFailure(call: Call<List<QuestionModel>>?, t: Throwable?) {
questionsList.clear()
}
})
return questionsList
}
答案 0 :(得分:0)
如果您要进入观察者的数据抛出任何异常,那么直到您再次设置该观察者或阻止该异常后,该观察者才会再次调用。
答案 1 :(得分:0)
如果要从存储库返回LiveData,可以执行以下操作:
在存储库中,将questionsList的类型更改为MutableLiveData,并在从回调返回时发布该值:
override fun getQuestions(): LiveData<QuestionModel> {
val questionsList = MutableLiveData<List<QuestionModel>>()
apiRequests?.questions()?.enqueue(object : retrofit2.Callback<List<QuestionModel>> {
override fun onResponse(
call: Call<List<QuestionModel>>?,
response: Response<List<QuestionModel>>
) {
response.body()?.let {
questionsList.postValue(response.body())
}
}
override fun onFailure(call: Call<List<QuestionModel>>?, t: Throwable?) {
questionsList.postValue(emptyList())
}
})
return questionsList
}
在ViewModel中,只需调用getQuestions():
class JobQuestionsViewModel @Inject constructor(private val repository: Repository) : ViewModel() {
val jobQuestions: LiveData<List<QuestionModel>> = repository.getQuestions()
}