简体   繁体   中英

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. app.loginAsync returns another object, and is not mine so I cannot change it. Is there a way that I can do this?

The app.loginAsync is a 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. 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()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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