Home > Software engineering >  Kotlin inline function for checking if user is autheticated or not?
Kotlin inline function for checking if user is autheticated or not?

Time:10-01

I want to execute a block of code after checking if user is authenticated or not. Something like this:

   inline fun <T : Any, R> T?.isUserAuthenticated(callback: (T) -> R) {
    FirebaseAuth.getInstance().currentUser?.let {
        //Function call
    } ?: kotlin.run {
        FirebaseAuth.getInstance().signInAnonymously().addOnSuccessListener { 
            //Function call
        }
    }

This approach isn't working, but is there any alternative to this?

CodePudding user response:

Inline functions in Kotlin should be used over regular functions when:

  • You desperately need to allocate memory more efficiently.
  • When a function accepts another function or lambda as an argument.
  • You need to prevent object creation and have better control flow.

Otherwise, inlining may cause the generated code to grow. Most likely there are also other situations when it is worth using inline functions but I only added a few (important) of them.

When it comes to checking if a user is authenticated or not, I would rather create a regular function that looks like this:

fun getAuthState() = auth.currentUser != null

And use it:

val isAuthenticated = getAuthState()
if(isAuthenticated) {
    auth.signInAnonymously().addOnCompleteListener(/*...*/)
}

Or if using Kotlin Coroutine:

if(isAuthenticated) {
    auth.signInAnonymously().await()
}

So it's one approach or the other.

I would add this function in a repository class so it can be used all across the entire project.

If you're interested in seeing some code, I recommend you check the following resource:

And here is the corresponding repo.

  • Related