简体   繁体   中英

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???
}

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)


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM