Search code examples
androidandroid-mvvm

how can I syncronize with mvvm?


I'm studying mvvm. When I call init(), the first call is null. using retrofit, I think the reason is that the function getIndexRetrofit() is returned before the line execute data.value = res. So I wanna syncronize this, expecting the function to return not null but the response values.

Repository:

fun getIndexRetrofit(name:String) : MutableLiveData<UserModel>{   

    Retrofit2Service.getService().requestUserInfo(name).enqueue(object: Callback<UserModel> {
        override fun onFailure(call: Call<UserModel>, t: Throwable) {
           data.postValue(null)
        }
        override fun onResponse(call: Call<UserModel>, response: Response<UserModel>) {
            if(response.body()!=null) {
                var res = response.body()!!

                data.value = res
            }
        }
    })//Retrofit

    return data
}

Solution

  • I can't say what getIndexRetrofit() suppose to do, but I believe you are misusing live data here. You are making asynchronous call Retrofit2Service.getService().requestUserInfo(name).enqueue It will be called, request will be made, but the result of execution is not yet received, at the same time return data will happen.

    Understand that onFailure() and onResponse() are callbacks, and the code will not be executed immediately. You code is not meant to be read sequentially top to bottom. Sequence of execution will be next

    1. Retrofit2Service.getService().requestUserInfo(name).enqueue
    2. return data
    3. onResponse() or onFailure()

    You should not return anything in getIndexRetrofit() instead refactor your function to look like that

    fun getIndexRetrofit(name:String) {   
        Retrofit2Service.getService().requestUserInfo(name).enqueue(object: Callback<UserModel> {
            override fun onFailure(call: Call<UserModel>, t: Throwable) {
               data.postValue(null)
            }
            override fun onResponse(call: Call<UserModel>, response: Response<UserModel>) {
                if(response.body()!=null) {
                    var res = response.body()!!
                    data.value = res
                }
            }
        })
    }