Avatar
0
andrenajordan Beginner
andrenajordan Beginner
Xử lí bất đồng bộ Asynchronous trong RESTful API

Em có 2 đoạn code như sau:

btn_start.setOnClickListener(view -> {
    if (txt_cms_address.getText() != null) {
        cmsAddress = txt_cms_address.getText().toString();
        Log.d(TAG, "CMS" + cmsAddress);
        APIRegisterDisplay();
//                APISchedule();
//                APIGetRequiredFile();
        if (checkConnect) {
//                    APIGetRequiredFile();
//                    APISchedule();
            Log.d(TAG, "check ok");
        } else {
            Log.d(TAG, "check k ok");
        }
    } else {
        Toast.makeText(this, "Address must not be empty!!", Toast.LENGTH_SHORT).show();
    }
});

Với các hàm APIRegisterDisplay(), APIGetRequiredFile(), APISchedule() là các asynchronous để dùng restful api bằng Retrofit2.

Vấn đề ở đây, khi em bấm vào btn, em chạy APIRegisterDisplay() trước, nếu kq từ api trả về = 0, hay biến checkConnect == true thì tiếp tục chạy 2 hàm APIGetRequiredFile() và APISchedule()

Vì là bất đồng bộ nên em không biết xử lí thế nào. Nếu trong if(checkConnect) ở đoạn code đầu, thì nó luôn trả về "check ko ok". Còn nếu bỏ trong if (display != null) ở đoạn code 2, thì hình như nó không chạy.

Mọi người có cách hay keyword nào về xử lí cái này có thể giúp em với ạ.

Em xin cảm ơn.

  • Answer
question
Remain: 5
3 Answers
Avatar
andrenajordan Beginner
và đây là đoạn code thứ 2
private void APIRegisterDisplay() {

    RegisterDisplay registerDisplay = new RegisterDisplay(abc, xyz ...);
    
    apiService = RetrofitClient.getClient(cmsAddress).create(APIService.class);
    apiService.Register(registerDisplay).enqueue(new Callback() {
        @Override
        public void onResponse(@NonNull Call call, @NonNull Response response) {
            if (response.isSuccessful()) {
                assert response.body() != null;
                JsonObject json = response.body().getAsJsonObject("response").getAsJsonObject("display").getAsJsonObject("$");

                Gson gson = new GsonBuilder().setPrettyPrinting().create();
                String string = gson.toJson(json);
                Display display = gson.fromJson(string, Display.class);

                if (display != null) {
                    if (display.getCode().equals("0")) {
                        //code == 0 Display is active and ready to start
                        Toast.makeText(getApplicationContext(), display.getMessage(), Toast.LENGTH_SHORT).show();
                        Log.d(TAG, "get display successful");

                        checkConnect = true;
                    } else {
                        Toast.makeText(getApplicationContext(), display.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Log.d(TAG, "failed");
                    Toast.makeText(getApplicationContext(), "Unable to connect to CMS!!", Toast.LENGTH_SHORT).show();
                }
            }
        }

        @Override
        public void onFailure(@NonNull Call call, @NonNull Throwable t) {
            Log.e(TAG, "REGISTER_DISPLAY:" + t.getLocalizedMessage());
        }
    });
}

Các bác chú ý biến checkConnect. Biến này để kiểm tra api trả về display.getCode() có bằng 0 (nghĩa là thành công) hay không.

  • 0
  • Reply
Avatar
andrenajordan Beginner
Bác nào hướng dẫn em post code để em edit lại với ạ, em dùng thẻ code trong editor nó sao sao ấy :(
  • 0
  • Reply
em dùng thẻ pre nhé, đang có 1 lỗi phát sinh liên quan đến phần format code, anh đang tìm cách khắc phục em nhé  –  tvd12 1631784062000
à ra vậy, em cảm ơn ạ  –  andrenajordan 1631784107000
Avatar
tvd12 Beginner
tvd12 Beginner
The Best Answer
anh thấy em chỉ cần chuyển 2 hàm APIGetRequiredFile() và APISchedule() vào onResponse là được, em đã thử chưa em?
  • 2
  • Reply
em cảm ơn anh, nó hoạt động đúng rồi

lỗi của em ở dòng if trong APIRegisterDisplay, nhờ anh em mới check lại và thấy chỗ sai ạ

 –  andrenajordan 1631843293000