postValue() 不会在 MutableLiveData 上调用观察

postValue() doesn't call observe on MutableLiveData

我有一个 API,我从中获得了一份来自邮政编码的地址列表。这是我进行 API 调用的地方,return 一个 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。为什么会这样?

您需要像下面那样做

 val interactor = RegistrationInteractor()
        
        interactor.addressLiveData.observe( viewLifecycleOwner, Observer {
            @Override
            fun onChanged(newAddresses: List<Address>) {
                //Set UI
                addressList.addAll(newAddresses)
                adapter.notifyDataSetChanged()
            }
        })

更新

不要从您的方法中 return 您的 MutableLiveData<List<Address>> 对象。只需获取 addressLiveData 的直接实例并将其用于 observe.