Liftric/cognito-idp

Return object from a Fold()

Burf2k opened this issue · 8 comments

Really sorry to ask, but I haven't done Kotlin for a few years so .fold is puzzling me. How do I return something out of a fold, from your samples, getUser gets the user, brilliant but how do I return it (User is my own class which takes UserAtributes)

    suspend fun getUser(accessToken: String) : User  {

        provider.getUser(accessToken ).fold(
            onSuccess = {
                print("login")
                currentUser = User.populateUserDetails(it)
                
                // does not compile as expects Unit, not User object
                return@fold currentUser
            },
            onFailure = {
                // Handle exceptions
                print(it.message)
            }
        )
    }

I asked StackoverFlow and that answer doesn't work, there must be a way to return something useful
https://stackoverflow.com/questions/76101500/kotlin-returning-an-object-from-a-fold-closure/76103361#76103361

This is more a question on Kotlin and how to work with suspend / Coroutines. But seeing the latest answer in this SO post I would infer that your problem is solved.

Thank you Ben, I just assumed there was a way we could use onSuccess and onFailure

Hi @Burf2k, there's indeed an issue with the fold extension. Since kotlin.Result couldn't get returned in the past and type information still gets lost when exported, we implemented our own Result type. Our fold extension doesn't return anything from onSuccess and onFailure.

https://github.com/Liftric/cognito-idp/blob/master/src/commonMain/kotlin/com/liftric/cognito/idp/core/Result.kt

So do I need to use your library or wait for a fix?

You could use getOrThrow to get the user, and wrap the call in a try/catch block to handle exceptions.

Thanks, glad I was not using Fold wrong

Fold is just like a promise in the JS world, you could wrap the "callbacks" with suspendCancellableCoroutine