0

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?

BArtWell
  • 4,176
  • 10
  • 63
  • 106

1 Answers1

1

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();
}
geekfreak.xyz
  • 90
  • 1
  • 9
  • Thank you for answer. Could you please explain a little? What is dispatcher object? Can I use it in UI thread? – BArtWell Jun 23 '17 at 16:58
  • 1
    Whenever your changes the screen or any event executes, or call a method in the code-behind all this happen in the UI thread and UI thread queue the called method into the Dispatcher queue....IF you like it Thumbs Up my man – geekfreak.xyz Jun 23 '17 at 16:59
  • I can't find any information about Dispatcher class in Android reference. Where I can get information about this? – BArtWell Jun 23 '17 at 17:19