https://kotlinlang.org logo
#getting-started
Title
# getting-started
d

Daniel

03/10/2023, 12:07 PM
Is this the correct way that the flow is executed?
Copy code
suspend fun Logout(token: String) {
    val userId = appService.currentUser!!.id       ///// this will execute 1st
    realm.write {                                  ///// this will execute 2nd
        var user = query<UserInfo>("_id = $0", userId).first().find()
        if (user != null) {
            user = findLatest(user)!!.also {
                it.FCMToken.remove(token)
            }
            copyToRealm(user)
        }
    }
    withContext(Dispatchers.Default) {             ///// this will execute 3rd

        realm.syncSession.uploadAllLocalChanges()  ///// this will execute 4rd

        appService.currentUser?.logOut()           ///// this will execute 5th
    }
}
Are they executed in a linear way?
s

Stephan Schröder

03/11/2023, 10:25 AM
to the best of my knowledge derived from tutorials your statements are executed linearly. In a totally unrelated matter, let's get rid of the not-null-assertion operator
!!
. Since a logout doesn't make sense, if there isn't a currentUser, let's simply return from the function, should for some strange reason (maybe a race condition 🤷‍♂️) currentUser be null
Copy code
val userId = appService.currentUser?.id ?: return
let's remove some other issues •
appService.currentUser
is invoked twice though it's mutable and might not return the same instance • there's another
!!
• let's replace the
var
with a
val
• the
also
isn't necessary • the method starts with a capital letter (this isn't Go, probably you have a codestyle, but I'll "fix" it in my suggestion anyway) This gives us:
Copy code
suspend fun logout(token: String) {
    val currentUser = appService.currentUser ?: return
    realm.write {
        query<UserInfo>("_id = $0", currentUser.id).first().find()?.let { user ->
            val latestUser = findLatest(user) ?: run {
                log.warn("strange db inconsistency: findLatest didn't return a user after a user query retrieved an instance from id ${currentUser.id}. defaulting to first found instance")
                user
            }
            latestUser.fcmToken.remove(token)
            copyToRealm(latestUser)
        }
    }
    withContext(Dispatchers.Default) {
        realm.syncSession.uploadAllLocalChanges()
        currentUser.logOut()
    }
}
It's not completely clear if my
log.warn
is sufficient, or if an exception should be thrown. At least an exception thrown would have more info than the
NullPointerException
thrown by the initial
!!
. The exception version would look like this
Copy code
val latestUser = findLatest(user) ?: error("strange db inconsistency: findLatest didn't return a user after a user query retrieved an instance from id ${currentUser.id}. defaulting to first found instance")
5 Views