Skip to content

Instantly share code, notes, and snippets.

@PhantomCh
Created April 20, 2023 12:05
Show Gist options
  • Save PhantomCh/4b63d8bfb7116a27ea414eaedc763fa4 to your computer and use it in GitHub Desktop.
Save PhantomCh/4b63d8bfb7116a27ea414eaedc763fa4 to your computer and use it in GitHub Desktop.
public class BleCommandExecutor implements CommandExecutor {
private final BleDevice bleDevice;
private final Executor executor = Executors.newSingleThreadExecutor();
private final Map<String, Queue<CommandCallback<String>>> callbacks = new ConcurrentHashMap<>();
public BleCommandExecutor(BleDevice bleDevice) {
this.bleDevice = bleDevice;
}
@Override
public void requestAsync(@NonNull String command, CommandCallback<String> callback) {
Queue<CommandCallback<String>> callbacksQueue = callbacks.get(command);
if (callbacksQueue != null) {
callbacksQueue.add(callback);
} else {
callbacksQueue = new ConcurrentLinkedQueue<>();
callbacksQueue.add(callback);
callbacks.put(command, callbacksQueue);
executor.execute(() -> {
String result = bleDevice.requestSync(command);
Queue<CommandCallback<String>> cbQueue = callbacks.remove(command);
if (cbQueue != null) {
for (CommandCallback<String> cb : cbQueue) {
cb.onResponse(result);
}
}
});
}
}
}
@ildar2
Copy link

ildar2 commented Apr 20, 2023

лучше newFixedThreadPool вместо newSingleThreadExecutor, а то долго отрабатывает

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment