Home

Awesome

<h1 align="left">Firebase Kotlin SDK <img alt="GitHub last commit" src="https://img.shields.io/github/last-commit/gitliveapp/firebase-kotlin-sdk?style=flat-square"> <a href="https://git.live"><img src="https://img.shields.io/endpoint?style=flatsquare&url=https%3A%2F%2Fteamhub-dev.web.app%2Fbadge%3Forg%3DGitLiveApp%26repo%3Dfirebase-kotlin-sdk"></a></h1> <img align="left" width="75px" src="https://avatars2.githubusercontent.com/u/42865805?s=200&v=4"> <b>Built and maintained with 🧡 by <a href="https://git.live">GitLive</a></b><br/> <i>Development teams merge faster with GitLive</i><br/> <br/> <br/> The Firebase Kotlin SDK is a Kotlin-first SDK for Firebase. It's API is similar to the <a href="https://firebase.github.io/firebase-android-sdk/reference/kotlin/firebase-ktx/">Firebase Android SDK Kotlin Extensions</a> but also supports multiplatform projects, enabling you to use Firebase directly from your common source targeting <strong>iOS</strong>, <strong>Android</strong>, <strong>Desktop</strong> or <strong>Web</strong>, enabling the use of Firebase as a backend for <a href="https://www.jetbrains.com/lp/compose-multiplatform/">Compose Multiplatform</a>, for example.

Available libraries

The following libraries are available for the various Firebase products.

Service or ProductGradle DependencyAPI Coverage
Analyticsdev.gitlive:firebase-analytics:2.1.080%
Authenticationdev.gitlive:firebase-auth:2.1.080%
Realtime Databasedev.gitlive:firebase-database:2.1.070%
Cloud Firestoredev.gitlive:firebase-firestore:2.1.060%
Cloud Functionsdev.gitlive:firebase-functions:2.1.080%
Cloud Messagingdev.gitlive:firebase-messaging:2.1.01%
Cloud Storagedev.gitlive:firebase-storage:2.1.040%
Installationsdev.gitlive:firebase-installations:2.1.090%
Remote Configdev.gitlive:firebase-config:2.1.020%
Performancedev.gitlive:firebase-perf:2.1.01%
Crashlyticsdev.gitlive:firebase-crashlytics:2.1.080%

Is the Firebase library or API you need missing? Create an issue to request additional API coverage or be awesome and submit a PR

Kotlin-first design

Unlike the Kotlin Extensions for the Firebase Android SDK this project does not extend a Java based SDK so we get the full power of Kotlin including coroutines and serialization!

<h3><a href="https://kotlinlang.org/docs/tutorials/coroutines/async-programming.html#coroutines">Suspending functions</a></h3>

Asynchronous operations that return a single or no value are represented by suspending functions in the SDK instead of callbacks, listeners or OS specific types such as Task, for example:

suspend fun signInWithCustomToken(token: String): AuthResult

It is important to remember that unlike a callback based API, wating for suspending functions to complete is implicit and so if you don't want to wait for the result you can launch a new coroutine:

//TODO don't use GlobalScope
GlobalScope.launch {
  Firebase.auth.signOut()
}
<h3><a href="https://kotlinlang.org/docs/reference/coroutines/flow.html">Flows</a></h3>

Asynchronous streams of values are represented by Flows in the SDK instead of repeatedly invoked callbacks or listeners, for example:

val snapshots: Flow<DocumentSnapshot>

The flows are cold, which means a new listener is added every time a terminal operator is applied to the resulting flow. A buffer with the default size is used to buffer values received from the listener, use the buffer operator on the flow to specify a user-defined value and to control what happens when data is produced faster than consumed, i.e. to control the back-pressure behavior. Often you are only interested in the latest value received, in this case you can use the conflate operator to disable buffering.

The listener is removed once the flow completes or is cancelled.

<h3><a href="https://github.com/Kotlin/kotlinx.serialization">Serialization</a></h3>

The official Firebase SDKs use different platform-specific ways to support writing data with and without custom classes in Cloud Firestore, Realtime Database and Functions.

The Firebase Kotlin SDK uses Kotlin serialization to read and write custom classes to Firebase. To use Kotlin serialization in your project add the plugin to your gradle file:

plugins {
    kotlin("multiplatform") version "1.9.20" // or kotlin("jvm") or any other kotlin plugin
    kotlin("plugin.serialization") version "1.9.20"
}

Then mark your custom classes @Serializable:

@Serializable
data class City(val name: String)

Instances of these classes can now be passed along with their serializer to the SDK:

db.collection("cities").document("LA").set(City.serializer(), city) { encodeDefaults = true }

The buildSettings closure is optional and allows for configuring serialization behaviour.

Setting the encodeDefaults parameter is optional and defaults to true, set this to false to omit writing optional properties if they are equal to theirs default values. Using @EncodeDefault on properties is a recommended way to locally override the behavior set with encodeDefaults.

You can also omit the serializer if it can be inferred using serializer<KType>(). To support contextual serialization or open polymorphism the serializersModule can be overridden in the buildSettings closure:

@Serializable
abstract class AbstractCity {
    abstract val name: String
}

@Serializable
@SerialName("capital")
data class Capital(override val name: String, val isSeatOfGovernment: Boolean) : AbstractCity()

val module = SerializersModule {
    polymorphic(AbstractCity::class, AbstractCity.serializer()) {
        subclass(Capital::class, Capital.serializer())
    }
}

val city = Capital("London", true)
db.collection("cities").document("UK").set(AbstractCity.serializer(), city) { 
    encodeDefaults = true
    serializersModule = module
    
}
val storedCity = db.collection("cities").document("UK").get().data(AbstractCity.serializer()) {
    serializersModule = module
}
<h4><a href="https://firebase.google.com/docs/firestore/manage-data/add-data#server_timestamp">Server Timestamp</a></h3>

Firestore and the Realtime Database provide a sentinel value you can use to set a field in your document to a server timestamp. So you can use these values in custom classes:

@Serializable
data class Post(
    // In case using Realtime Database.
    val timestamp = ServerValue.TIMESTAMP,
    // In case using Cloud Firestore.
    val timestamp: Timestamp = Timestamp.ServerTimestamp,
    // or
    val alternativeTimestamp = FieldValue.serverTimestamp,
    // or
    @Serializable(with = DoubleAsTimestampSerializer::class),
    val doubleTimestamp: Double = DoubleAsTimestampSerializer.serverTimestamp
)

In addition firebase-firestore provides [GeoPoint] and [DocumentReference] classes which allow persisting geo points and document references in a native way:

@Serializable
data class PointOfInterest(
    val reference: DocumentReference, 
    val location: GeoPoint
)
val document = PointOfInterest(
    reference = Firebase.firestore.collection("foo").document("bar"),
    location = GeoPoint(51.939, 4.506)
)
<h4>Polymorphic serialization (sealed classes)</h4>

This sdk will handle polymorphic serialization automatically if you have a sealed class and its children marked as Serializable. It will include a type property that will be used to discriminate which child class is the serialized.

You can change this type property by using the @FirebaseClassDiscrminator annotation in the parent sealed class:

@Serializable
@FirebaseClassDiscriminator("class")
sealed class Parent {
    @Serializable
    @SerialName("child")
    data class Child(
        val property: Boolean
    ) : Parent
}

In combination with a SerialName specified for the child class, you have full control over the serialized data. In this case it will be:

{
  "class": "child",
  "property": true
}
<h3><a href="https://kotlinlang.org/docs/reference/functions.html#default-arguments">Default arguments</a></h3>

To reduce boilerplate, default arguments are used in the places where the Firebase Android SDK employs the builder pattern:

UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
        .setDisplayName("Jane Q. User")
        .setPhotoUri(Uri.parse("https://example.com/jane-q-user/profile.jpg"))
        .build()

user.updateProfile(profileUpdates)
        .addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                if (task.isSuccessful()) {
                    Log.d(TAG, "User profile updated.")
                }
            }
        })

//...becomes...

user.updateProfile(displayName = "Jane Q. User", photoURL = "https://example.com/jane-q-user/profile.jpg")
<h3><a href="https://kotlinlang.org/docs/functions.html#infix-notation">Infix notation</a></h3>

To improve readability and reduce boilerplate for functions such as the Cloud Firestore query operators are built with infix notation:

citiesRef.whereEqualTo("state", "CA")
citiesRef.whereArrayContains("regions", "west_coast")
citiesRef.where(Filter.and(
    Filter.equalTo("state", "CA"),
    Filter.or(
        Filter.equalTo("capital", true),
        Filter.greaterThanOrEqualTo("population", 1000000)
    )
))

//...becomes...

citiesRef.where { "state" equalTo "CA" }
citiesRef.where { "regions" contains "west_coast" }
citiesRef.where {
    all(
        "state" equalTo "CA",
        any(
            "capital" equalTo true,
            "population" greaterThanOrEqualTo 1000000
        )
    )
}
<h3><a href="https://kotlinlang.org/docs/reference/operator-overloading.html">Operator overloading</a></h3>

In cases where it makes sense, such as Firebase Functions HTTPS Callable, operator overloading is used:

    val addMessage = functions.getHttpsCallable("addMessage")
    //In the official android Firebase SDK this would be addMessage.call(...)
    addMessage(mapOf("text" to text, "push" to true))

Multiplatform

The Firebase Kotlin SDK provides a common API to access Firebase for projects targeting iOS, Android, JVM and JS meaning you can use Firebase directly in your common code. Under the hood, the SDK achieves this by binding to the respective official Firebase SDK for each supported platform.

It uses the <a href="https://github.com/GitLiveApp/firebase-java-sdk">Firebase Java SDK</a> to support the JVM target. The library requires additional initialization compared to the official Firebase SDKs.

Accessing the underlying Firebase SDK

In some cases you might want to access the underlying official Firebase SDK in platform specific code, for example when the common API is missing the functionality you need. For this purpose each class in the SDK has android, ios and js extension properties that hold the equivalent object of the underlying official Firebase SDK. For JVM, as the firebase-java-sdk is a direct port of the Firebase Android SDK, is it also accessed via the android property.

These properties are only accessible from the equivalent target's source set. For example to disable persistence in Cloud Firestore on Android you can write the following in your Android specific code (e.g. androidMain or androidTest):

  Firebase.firestore.android.firestoreSettings = FirebaseFirestoreSettings.Builder(Firebase.firestore.android.firestoreSettings)
          .setPersistenceEnabled(false)
          .build()

Running on Android

On android, some modules (config) require you to enable Core library desugaring if you have a minSDK lower than API 26.

Running on iOS

On iOS the official Firebase iOS SDK in not linked as a transitive dependency. Therefore, any project using this SDK needs to link the actual Firestore SDK as well. This can be done through your preferred installation method (Cocoapods/SPM).

Similarly, tests require linking as well. Make sure to add the required frameworks to the search path of your test targets. This can be done by specifying a cocoapods block in your build.gradle:

cocoapods {
   pod("FirebaseCore") // Repeat for Firebase pods required by your project, e.g FirebaseFirestore for the `firebase-firestore` module.
}

Contributing

If you'd like to contribute to this project then you can fork this repository. You can build and test the project locally.

  1. Open the project in IntelliJ IDEA.
  2. Install cocoapods via sudo gem install -n /usr/local/bin cocoapods
  3. Install the GitLive plugin into IntelliJ
  4. After a gradle sync then run publishToMavenLocal

Testing

To run the tests you can use the following gradle tasks:

./gradlew connectedAndroidTest (an emulator needs to be running)

./gradlew iosSimulatorArm64Test (On Apple Chip) ./gradlew iosX64Test (On Intel Chip)

./gradlew jsNodeTest

./gradlew jvmTest

For some tests you need to have the firebase emulator suite running. After installing them you can run the following command inside the test directory:

firebase emulators:start

Documentation

For every publicly available class or function there needs to be documentation written in the KDoc syntax. We publish a new version of the documentation after every release and can be found here

Validation

To ensure changes to the public API are well documented, this library validates its binary API. If you make changes to the API, make sure to run

./gradlew apiDump

Code style

This library uses the Intellij Kotlin code style. Run the linter to make sure you follow these styles.

./gradlew formatKotlin to format to the proper style ./gradlew lintKotlin to validate the correct style is used

Compatibility with the official Firebase Android SDK

When this project began, the official Firebase Android SDK was a pure java library and the separate Kotlin extensions (KTX) module consisted of only a few extensions providing some syntactic sugar, for example Firebase.firestore instead of Firebase.getInstance(), which we naturally copied for the Firebase Kotlin SDK.

But with the majority of the Android SDK being designed for Java, the Kotlin SDK was primarily guided by our Kotlin-first design principles.

More recently, with the official SDK for Android providing better support for Kotlin and the inclusion of the new Kotlin-friendly features direct in the main modules, the API differences between the official SDK and this project are likely to start to blur. Therefore, in particular for developers porting android code to multiplatform, one of our goals going forward will be API compatibility with the Android SDK where possible.

For contributors this means following these points when adding new code to the public API of this project: