简体   繁体   English

Kotlin - 从不返回 boolean 的异步任务返回 Boolean

[英]Kotlin - Return a Boolean from an async task that does not return a boolean

I'm attempting to return a boolean from the following function.我正在尝试从以下 function 返回 boolean。 app.loginAsync returns another object, and is not mine so I cannot change it. app.loginAsync 返回另一个 object,不是我的,所以我无法更改。 Is there a way that I can do this?有没有办法我可以做到这一点?

The app.loginAsync is a MongoDB Realm function. app.loginAsync 是 MongoDB Realm function。

fun login(email: String, password: String): Boolean {
    val credentials = Credentials.emailPassword(email, password)
    app.loginAsync(credentials) {
        if (!it.isSuccess) {
            return false
        } else {
            return true
        }
    }
}

You can do this with CompletableDeferred.您可以使用 CompletableDeferred 来做到这一点。 Try something like that:尝试这样的事情:

suspend fun login(email: String, password: String): Boolean {
    val completableDeferred = CompletableDeferred<Boolean>() 
    val credentials = Credentials.emailPassword(email, password)
    app.loginAsync(credentials) {
        completableDeferred.complete(it.isSuccess)
    }
    return completableDeferred.await()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM