简体   繁体   中英

Android, Retrofit 2: How to make calls every 5 second?

this is my code:

 private void getUserData(){
    //create Retrofit instance
    Retrofit.Builder builder = new Retrofit.Builder()
            .baseUrl(Constants.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create());

    Retrofit retrofit = builder.build();

    //get client & call object for the request
    APIService userService = retrofit.create(APIService.class);

    Map<String, Object> map = new HashMap<>();
    map.put("device_id", Utils.GetDeviceID(DashboardActivity.this));

    Call call = userService.getUser(map);

    //execute network request
    call.enqueue(new Callback() {
        @Override
        public void onResponse(Call call, Response response) {
            if(response.isSuccessful() && response.body() != null){
                response.body();
                UserDataManager.$().setUserDataResponse(new com.google.gson.Gson().toJson(response.body()));
                if(UserDataManager.$().getUserData() != null){
                    Log.d(TAG, "USER ID: " + UserDataManager.$().getUserData().getId());
                }
            }
        }

        @Override
        public void onFailure(Call call, Throwable t) {

        }
    });
}

Question: How can i call this method every 5 second, to check is the new data coming from backend or not?

Will be glad for suggestions and hints, thanks

RxAndroid will be very useful in this case. You can create loop like this

Subscription subscription = Observable.interval(1000, 5000, 
 TimeUnit.MILLISECONDS)
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Action1<Long>() {
            public void call(Long aLong) {
                // here is the task that should repeat
            }
        });

If you want to stop the loop just call

subscription.unsubscribe()

You can use Handler to achieve making call every 5 seconds.

boolean shouldStopLoop = false;
Handler mHandler = new Handler();

Runnable runnable = new Runnable() {
    @Override
    public void run() {
        getUserData();
        if (!shouldStopLoop) {
            mHandler.postDelayed(this, 5000);
        }
    }
};

and call mHandler.post(runnable); to start the call.

Completable.timer(5, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this::doYourThing, this::onError)) 

But a better option would be to ask your backend developer to send a firebase notification in case of a data change since Network calls are expensive operations.

workmanager将帮助您检查文档

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