FirebaseApp Client in Scala
How to properly load the FirebaseAuth Java client in Scala
While I was using the FirebaseAuth Java client, I was getting this error:
Execution exception[[IllegalStateException: FirebaseApp name [DEFAULT] already exists!]]
When my Play application reloaded itself, FirebaseApp.initializeApp() was getting called again from the application loader, which caused this error.
I made a simple wrapper to handle this:
import com.google.auth.oauth2.GoogleCredentials
import com.google.firebase.{ FirebaseOptions, FirebaseApp }
import scala.util.Try
object FirebaseAppLoader {
def apply(credentials: GoogleCredentials): FirebaseApp = {
Try(FirebaseApp.getInstance()).toEither match {
// App hasn't been initialized yet, so we initialize it
case Left(_: IllegalStateException) =>
FirebaseApp.initializeApp(
new FirebaseOptions.Builder()
.setCredentials(credentials)
.build
)
// Reuse the already-initialized app
case Right(app) => app
// Some other exception occurred
case Left(e) => throw e
}
}
}
We simply just try to get the Firebase app instance (wrapped in a Try), and if it doesn't exist, we initialize it, which should happen just once.
Using this wrapper is as simple as val firebaseApp: FirebaseApp = FirebaseAppLoader(credentials). Or with macwire, val firebaseApp: FirebaseApp = wireWith(FirebaseAppLoader(_)).
Export as PDF
Copy link