我有一个API,可以从邮政编码获取地址列表。我在这里进行API调用,并返回一个MutableLiveData对象,然后我尝试观察该对象
fun getAddressFromPostCode(postCode: String): MutableLiveData<List<Address>>{
val trimmedPostCode = postCode.replace("\\s".toRegex(),"").trim()
val dataBody = JSONObject("""{"postcode":"$trimmedPostCode"}""").toString()
val hmac = HMAC()
val hmacResult = hmac.sign(RequestConstants.CSSecretKey, dataBody)
val postData = PostCodeBodyData()
postData.postcode = trimmedPostCode
val body = PostCodeRequestData()
body.dataSignature = hmacResult
body.data = postData
//val myBodyModel = MyBodyModel(data = dataBody, data_signature = hmacResult)
val url = RequestConstants.CS_BASE_URL
val retrofit: Retrofit = Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build()
val api:GetAddressAPIService = retrofit.create(GetAddressAPIService ::class.java)
val myCall: Call<GetAddressResponse> = api.getPostCodeAddress(body)
myCall.enqueue(object : Callback<GetAddressResponse> {
override fun onFailure(call: Call<GetAddressResponse>?, t: Throwable?) {
Log.d("RegistrationInteractor", "Something went wrong", t)
Log.d("RegistrationInteractor", call.toString())
}
override fun onResponse(call: Call<GetAddressResponse>?, response: Response<GetAddressResponse>?) {
// Success response
if(response?.body()?.success == 1){
addressLiveData.postValue(response!!.body()!!.addresses)
}else{
Log.d("", response!!.body()?.serError?.errorDescription)
addressLiveData.postValue(null)
}
}
})
return addressLiveData
}
然后我在我的PostCodeFragment中收听:
btn_find_address.setOnClickListener {
val interactor = RegistrationInteractor()
addresses = interactor.getAddressFromPostCode(et_register_postcode.text.toString())
lifecycle.addObserver(interactor)
addresses.observe( viewLifecycleOwner, Observer {
@Override
fun onChanged(newAddresses: List<Address>) {
//Set UI
addressList.addAll(newAddresses)
adapter.notifyDataSetChanged()
}
})
}
但是onChanged永远不会被调用。为什么会这样?
答案 0 :(得分:1)
您需要执行以下操作
val interactor = RegistrationInteractor()
interactor.addressLiveData.observe( viewLifecycleOwner, Observer {
@Override
fun onChanged(newAddresses: List<Address>) {
//Set UI
addressList.addAll(newAddresses)
adapter.notifyDataSetChanged()
}
})
更新
不要从方法中返回MutableLiveData<List<Address>>
对象。只需获取您的addressLiveData
的直接实例并将其用于observe
。