Created
April 20, 2023 12:05
-
-
Save PhantomCh/4b63d8bfb7116a27ea414eaedc763fa4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
лучше
newFixedThreadPool
вместоnewSingleThreadExecutor
, а то долго отрабатывает