Reputation: 10948
I have a "+" and "-" button that will increase/decrease the quantity of an item.
I need to send a network request (hitting webservice) everytime the quantity is changed.
The problem is, the User probably will "spam" the "+" and "-" button. For example, they might pressed it 3 times in a second.
In regard of this case, I would like to wait a second, and then send the network request based on the last quantity. This is to reduce the number of requests i need to do (from 3 requests to just 1 request, in this case).
What is the recommended way to do this?
Can I solve this problem by using postDelayed
in my OnClick
?
Upvotes: 1
Views: 536
Reputation: 3711
As an update to Ivan's answer and fixed two issues:
The postDelayed is not needed for your logic and adds and extra 1 second delay
Move the update to lastClick into the loop we only want it to update when we actually trigger a network call.
Example
private long lastClick;
void onClick(View view) {
// Check if network call has been made in last second
if (System.currentTimeMillis() - lastClick >= 1000) {
// Mark time of network call
lastClick = System.currentTimeMillis();
makeNetworkRequest();
}
}
Upvotes: 0
Reputation: 400
I think you can try something like this
private long lastClick;
void onClick(View view) {
lastClick = System.currentTimeMillis();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if (System.currentTimeMillis() - lastClick >= 1000) {
makeNetworkRequest();
}
}
}, 1000);
}
This code will skip first requests and run only last request after 1 second pause
Upvotes: 1