在我的视图模型中,我有 2 个返回相同对象的 api 调用。但是,我创建了 2 个不同的 MutableLiveData 对象,但我无法观察到第二个对象。
这是我的代码片段
private fun initObservables() {
holidayViewModel.progressDialog?.observe(this, Observer {
if (it!!) customeProgressDialog?.show() else customeProgressDialog?.dismiss()
})
holidayViewModel.apiResponse?.observe(
viewLifecycleOwner,
androidx.lifecycle.Observer { response ->
if (response.dataList != null) {
response.dataList!!.removeAt(0)
if (requireArguments().getString("file_type")
.equals(NetworkConstant.FILE_TYPE_LOH, ignoreCase = true)
) {
val data = Data()
data.CountryId = "0"
data.CountryName = "Main organisation"
response.dataList!!.add(0, data)
}
val holidayAdapter = CountryAdapter(response.dataList)
binding.holiday.adapter = holidayAdapter
holidayAdapter.notifyDataSetChanged()
holidayAdapter.setListener(this)
}
})
holidayViewModel.pdfLink?.observe(
viewLifecycleOwner,
androidx.lifecycle.Observer { response ->
utils.openPdf(response.dataList!!.get(0)?.filePath)
})
}
这是视图模型类
class HolidayViewModel(networkCall: NetworkCall) : ViewModel() {
var progressDialog: SingleLiveEvent<Boolean>? = null
var apiResponse: MutableLiveData<ApiResponse>? = null
var pdfLink: MutableLiveData<ApiResponse>? = null
var networkCall: NetworkCall;
init {
progressDialog = SingleLiveEvent<Boolean>()
apiResponse = MutableLiveData<ApiResponse>()
this.networkCall = networkCall
}
fun countries(username: String?, userId: String?) {
progressDialog?.value = true
val apiPost = ApiPost()
apiPost.userName = username
apiPost.UserId = userId
networkCall.getCountries(apiPost).enqueue(object : Callback<ApiResponse?> {
override fun onResponse(
call: Call<ApiResponse?>,
response: Response<ApiResponse?>
) {
progressDialog?.value = false
apiResponse?.value = response.body()
}
override fun onFailure(
call: Call<ApiResponse?>,
t: Throwable
) {
progressDialog?.value = false
}
})
}
fun fetchPdf(
username: String?,
password: String?,
userId: String?,
countryId: String?,
fileType: String?
) {
progressDialog?.value = true
val apiPost = ApiPost()
apiPost.userName = username
apiPost.password = password
apiPost.UserId = userId
apiPost.CountryId = countryId
apiPost.FileType = fileType
networkCall.getPDF(apiPost).enqueue(object : Callback<ApiResponse?> {
override fun onResponse(
call: Call<ApiResponse?>,
response: Response<ApiResponse?>
) {
progressDialog?.value = false
pdfLink?.value = response.body()
}
override fun onFailure(
call: Call<ApiResponse?>,
t: Throwable
) {
progressDialog?.value = false
}
})
}
}
我正在尝试观察pdfLink
对象,但是调用了API,但我从未在片段中收到该对象的回调。
这是怎么回事?
问题是pdfLink
在视图模型中始终为空。
您已声明var pdfLink: MutableLiveData<ApiResponse>? = null
但尚未初始化。而且由于您是空的,因此使用?
检查它,它永远不会引发异常。
试试这个:
init {
progressDialog = SingleLiveEvent<Boolean>()
apiResponse = MutableLiveData<ApiResponse>()
pdfLink = MutableLiveData<ApiResponse>() // Add this line inside init
this.networkCall = networkCall
}
一个愚蠢的错误忘记初始化它
pdfLink = MutableLiveData<ApiResponse>()