Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LionZXY/45e18aeedf9f78bc26be37f82de6a32a to your computer and use it in GitHub Desktop.
Save LionZXY/45e18aeedf9f78bc26be37f82de6a32a 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);
}
}
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment