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:
1
import com.google.auth.oauth2.GoogleCredentials
2
import com.google.firebase.{ FirebaseOptions, FirebaseApp }
3
4
import scala.util.Try
5
6
object FirebaseAppLoader {
7
def apply(credentials: GoogleCredentials): FirebaseApp = {
8
Try(FirebaseApp.getInstance()).toEither match {
9
// App hasn't been initialized yet, so we initialize it
10
case Left(_: IllegalStateException) =>
11
FirebaseApp.initializeApp(
12
new FirebaseOptions.Builder()
13
.setCredentials(credentials)
14
.build
15
)
16
// Reuse the already-initialized app
17
case Right(app) => app
18
// Some other exception occurred
19
case Left(e) => throw e
20
}
21
}
22
}
Copied!
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(_)).
Last modified 2yr ago
Export as PDF
Copy link