Search code examples
javaandroidretrofit2

Get boolean value from Retrofit2 onResponse


I am trying to make an asynchronous request to the server, which should return me true or false. But the problem is that the function first returns false, and only then the retrofit function is triggered. How can I get the value I need while maintaining the speed of program execution? My code:

private static boolean find;
public boolean checkAccountByPhone(String phone){

    Log.d("dbHandler", "function started...");

    DbHandler.getApi().checkAccountByPhone(phone).enqueue(new Callback<String>() {
        @Override
        public void onResponse(Call<String> call, Response<String> response) {
            Log.d("dbHandler", "data is: "+response.body().equals("true"));

            // return response.body().equals("true");

            Log.d("dbHandler", "sent!");

        }
        @Override
        public void onFailure(Call<String> call, Throwable t) {
            Log.d("dbHandler", t.getMessage());
        }
    });

    Log.d("dbHandler", "returned: "+DbHandler.find);
    return DbHandler.find; // always false???
}

Solution

  • You can modify logic in Java, this code is for reference to avoid callback.

     fun checkAccountByPhone(phone: String):String{
        viewModelScope.launch(Dispatchers.IO) {
            val response : Response<String> = try {
                DbHandler.getApi().checkAccountByPhone(phone)
            } catch (ex: Exception) {
                ex.logException()
                null
            }
    
            //you can check response.body() here and can post either response.body() or DbHandler.find
            _yourLiveData.post(response.body() or DbHandler.find)
    
    
    }