completableFuture.complete() 在 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。问题是,如果我不等待 FutureToast 会正确显示。如果我等待 Future 应用程序冻结。我的猜测是 CompletableFuture.complete() 不能从 addOnSuccessListener 调用,但这很奇怪,因为对 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()
    // ...
}