0
How to create a simple promise on a dedicated thread
I'm trying to create a simple http request, repeated once per second that call a post on an UI handler everytime it gets the remote json string. Im confused about how to repeat the request without blocking the UI and at the same tine handling the response of the server
2 Answers
+ 4
Look for socket connections and flow control protocol.
websockets allow you to exchange data in real time, flow control eliminates the risk of your ui getting blocked due to data overflow.
a simple flow control protocol may look like this:
1 client requests new data
2 server receives request
3 sends data and waits for request
4 client receives data
5 processes data
...repeat over and over again.....
0
I've tried completablefuture but it's not globally supported. So now i'm using this but i get stackoverflow error after some time:
executorService = Executors.newFixedThreadPool(2);
Runnable r = new Runnable() {
@Override
public void run() {
while (true) {
handler.post(new Runnable() {
@Override
public void run() {
//ui update
}
});
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i("cc", Thread.currentThread().getName());
}
}
};
Runnable r2 = new Runnable() {
@Override
public void run() {
long t = System.currentTimeMillis();
ExecutorService ex = Executors.newSingleThreadExecutor();
Callable<OrderBook> c = new Callable<OrderBook>() {
@Override
public OrderBook call() throws Exception {
return Poloniex.createOrderBook(10, "USDT_ETH");
}
};
Future<OrderBook> f = ex.submit(c);
try{
ob = f.get();
}catch (InterruptedException e){
e.printStackTrace();
}catch (ExecutionException e){
e.printStackTrace();
}
long dt = 1000-(System.currentTimeMillis()-t);
dt = dt>0?dt:0;
try {
Thread.sleep(dt);
}catch(InterruptedException e){
e.printStackTrace();
}
Log.i("ff", Thread.currentThread().getName());
this.run();
}
};
executorService.execute(r);
executorService.execute(r2);