In my Android app I want to use java.util.concurrent tools to make operations that return value (for educational purposes). I read that CompletableFuture can be used for this. I made a project where I simulate an operation that takes some time to execute:
class MyRepository {
private var counter = 0
// Here we make a blocking call
fun makeRequest(): Int {
Thread.sleep(2000L)
counter += 1
return counter
}
}
Then I call this function from UI thread:
fun getNumber(): Int {
val completableFuture = CompletableFuture<Int>()
Executors.newCachedThreadPool().submit<Any?> {
val result = myRepository.makeRequest()
completableFuture.complete(result)
null
}
return completableFuture.get()
}
The problem is that UI is blocked while this operation is being executed. How can I use CompletableFuture to make operation like this without blocking UI of application?
I want to use only java.util.concurrent tools for this.
FutureTask.get()is a blocking call, which is why the UI freezes during its execution. Also, why not use coroutines?