Hi is there way to shorten this code ? ```overrid...
# getting-started
a
Hi is there way to shorten this code ?
Copy code
override suspend fun isLoginSessionValid(): Flow<Result<Boolean>> = flow {
    ParseUser.getCurrentUser()?.let { parseUser ->
        if (!parseUser.isAuthenticated)
            cleanupOnLogout()
        emit(Result.success(parseUser.isAuthenticated))
    } ?: kotlin.run {
        cleanupOnLogout()
        emit(Result.success(false))
    }
}
f
you have a
suspend
function that returns a
flow
. These don't go together. You are emitting a single value, so just make this a
suspend
function
Copy code
override suspend fun isLoginSessionValid(): Result<Boolean>  {
    ParseUser.getCurrentUser()?.let { parseUser ->
        if (!parseUser.isAuthenticated)
            cleanupOnLogout()
        return Result.success(parseUser.isAuthenticated)
    } ?: kotlin.run {
        cleanupOnLogout()
        return Result.success(false)
    }
}
👍 1
h
I would use a if/when instead, I like the "old" code stlye more then nested let run with
?:
. And you should not rely on
let ?: run
to run another action. because the last expression in the let lambda could change the execution of
run
💯 2
a
Copy code
if ( ParseUser.getCurrentUser()?.isAuthenticated == true) {
// emit success here
} else{
// handle case when null or false here assuming you want to do the same thing when the value is null or false
}
2
k
Copy code
override suspend fun isLoginSessionValid() = Result.success(
   ParseUser.getCurrentUser()?.isAuthenticated == true || run { cleanupOnLogout(); false }
)
1
h
And like @Francesc already said: use a simple suspend function. And don't use suspend modifier while returning an (async) flow. Aaaand if this is the whole function, I don't see a reason to use
Result
at all 😄
Copy code
override suspend fun isLoginSessionValid(): Boolean {
    val parseUser = ParseUser.getCurrentUser()
    return if (parseUser != null && parseUser.isAuthenticated) true
    else {
        cleanupOnLogout()
        false
    }
}
1
p
Copy code
override suspend fun isLoginSessionValid() = (ParseUser.getCurrentUser()?.isAuthenticated ?: false)
    .also { if(!it) cleanupOnLogout() }
    .let { Result.success(it) } // if really needed
Arguably, making the code shorter shouldn’t necessarily be the goal but instead making it clear and concise.
2