BArtWell
BArtWell

Reputation: 4044

How to implement requests queue?

I have an application which uses methods from third-party SDK (async methods to make HTTP-requests to remote server) and Retrofit2 + OkHttp + Rx to access this server directly. It looks like this:

new SdkRequest("some", "arguments", "here")
    .setCompleteListener(this::onGetItemsComplete)
    .setErrorListener(this::onGetItemsError)
    .getItems(); // Here is can be differents methods (getShops, getUsers, etc)

ApiManager.getInstance()
    .getApi()
    .addAdmin("some", "another", "arguments", "here") // Methods which not presented in SDK we should call directly
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(this::onAddAdminComplete, this::onAddAdminError);

I need that the all requests (from SDK and from Retrofit) with limit - 5 request in 1 second max. When this limit is exceeded request should wait before continue.

How to implement it? The first thing that comes to mind - add Service and BroadcastReceiver. But it not so lazy for me: I should listening this BroadcastReceiver in every activity fragment, and here is no so useful callbacks with this implementation. Is it possible to implement it with Rx (wrap SDK methods also) and use lambdas?

Upvotes: 0

Views: 837

Answers (1)

geekfreak.xyz
geekfreak.xyz

Reputation: 90

You can do this easily, without extra threads or services, with a semaphore.

Semaphore s = new Semaphore(40);
...
s.acquire();
try {
    dispatcher.dispatchRpcRequest(); // Or whatever your remote call looks like
} finally {
    s.release();
}

Upvotes: 1

Related Questions