completableFuture.complete() 在 addOnSuccessListener 中不起作用

completableFuture.complete() not working inside addOnSuccessListener

我有以下代码:

private fun genericFunction(): CompletableFuture<Location?> {
    val completableFuture = CompletableFuture<Location?>()

    Executors.newCachedThreadPool().submit {
        val fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
        
        fusedLocationClient.lastLocation
                .addOnSuccessListener { location: Location? ->
                    Toast.makeText(...).show()
                    completableFuture.complete(location)
                }
    }
    
    return completableFuture
}

我希望能够从 addOnSuccessListener 侦听器完成 CompletableFuture。问题是,如果我不等待 Future,则会正确显示 Toast。如果我等待 Future 应用程序冻结。我的猜测是无法从 addOnSuccessListener 调用 completableFuture.complete(),但这很奇怪,因为对 completableFuture 的引用在 Listener.

中有效

知道问题出在哪里吗?我可以做些调试吗?

问题是我使用的是 CompletableFuture.allOf(...).get()

我通过更改解决了:

val currentLocationFuture = getCurrentLocation()
val currentActivityFuture = getCurrentActivity()
CompletableFuture.allOf(currentLocationFuture, currentActivityFuture).get()
val currentLocation = currentLocationFuture.get()
val currentActivity = currentActivityFuture.get()
// ...

至:

val currentLocationFuture = getCurrentLocation()
val currentActivityFuture = getCurrentActivity()
CompletableFuture.allOf(currentLocationFuture, currentActivityFuture).thenApply {
    val currentLocation = currentLocationFuture.get()
    val currentActivity = currentActivityFuture.get()
    // ...
}