Skip to content

Instantly share code, notes, and snippets.

  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
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