Alex Petev
Alex Petev

Reputation: 489

postValue() doesn't call observe on MutableLiveData

I have an API where I get a list of addresses from postcode. Here is where I make the API call, and return a MutableLiveData object that I then try to observe

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
}

I then listen for this in my 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()
            }
        })
    }

However onChanged never gets called. Why is this happening?

Upvotes: 0

Views: 571

Answers (1)

Mehul Kabaria
Mehul Kabaria

Reputation: 6622

You need to do like below

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

Update

Do not return your MutableLiveData<List<Address>> object from your method. Just get a direct instance of your addressLiveData and use it to observe.

Upvotes: 1

Related Questions