One Firebase Realtime

Firebase Realtime Database is a cloud-hosted NoSQL database that allows you to store and sync data between your users in real-time.

Checkout the full features here

Example Usage:

class RealtimeDataSourceOne : RealtimeRepository, OneFirebaseRealtime() {

    override val databaseRef: DatabaseReference =
        FirebaseDatabase.getInstance().getReference("users")

    override suspend fun realtimeAdd(data: RealtimeRequest): Flow<Resource<Boolean>> =
        callbackFlow {
            setValue(value = data.toMap()) {
                trySend(it)
            }

            awaitClose { this.close() }
        }

    override suspend fun realtimeRemove(id: String): Flow<Resource<Boolean>> = callbackFlow {
        removeValue(id = id) {
            trySend(it)
        }

        awaitClose { this.close() }
    }

    override suspend fun realtimeList(): Flow<Resource<List<RealtimeResponse>>> = callbackFlow {
        getListValue(
            clazz = RealtimeResponse::class.java,
            eventListener = { trySend(it) }
        )
        awaitClose { this.close() }
    }

    override suspend fun realtimeEdit(id: String): Flow<Resource<Boolean>> = callbackFlow {
        val value = hashMapOf<String, Any?>("name" to "wahid")

        updateValue(id = id, value = value) {
            trySend(it)
        }

        awaitClose(this::close)
    }

    override suspend fun getData(id: String): Flow<Resource<RealtimeResponse>> = callbackFlow {
        getValue(id = id, clazz = RealtimeResponse::class.java){ data ->
            trySend(data)
        }

        awaitClose(this::close)
    }
}

This is content of RequestModel and ResponseModel:

data class RealtimeRequest(
    val name: String? = null,
    val age: Int? = null
){
    @Exclude
    fun toMap() = hashMapOf<String, Any?>(
        "name" to name,
        "age" to age
    )
}

The RealtimeRequest data class is a Kotlin model used for sending data to a Firebase Realtime Database. It has two nullable properties: name (a string) and age (an integer), both initialized to null by default. The class includes a toMap function, marked with the @Exclude annotation (likely to prevent it from being serialized), which converts the object's properties into a HashMap with keys "name" and "age" mapped to their respective values. This toMap function facilitates the transformation of the data class into a format suitable for database operations in Firebase.

data class RealtimeResponse(
    val id: String? = null,
    val name: String? = null,
    val age: Int? = null
)

The RealtimeResponse data class is a Kotlin model designed to represent a response from a Firebase Realtime Database. It includes three nullable properties: id (a string for the unique identifier), name (a string for the name), and age (an integer for the age). Each property is initialized to null by default, making them optional. This class is typically used to map the data retrieved from the Realtime Database into a Kotlin object, allowing for easy access and manipulation of the database response data within an application.

And here content is RealtimeRepository

interface RealtimeRepository {
    suspend fun realtimeAdd(data: RealtimeRequest): Flow<Resource<Boolean>>
    suspend fun realtimeRemove(id: String): Flow<Resource<Boolean>>
    suspend fun realtimeList(): Flow<Resource<List<RealtimeResponse>>>
    suspend fun realtimeEdit(id: String): Flow<Resource<Boolean>>
    suspend fun getData(id: String): Flow<Resource<RealtimeResponse>>
}

Explanation:

Class and Interfaces

class RealtimeDataSourceOne : RealtimeRepository, OneFirebaseRealtime()

This line declares the RealtimeDataSourceOne class which implements the RealtimeRepository interface and extends OneFirebaseRealtime. This means it must provide concrete implementations for the methods defined in RealtimeRepository.

Properties

override val databaseRef: DatabaseReference = FirebaseDatabase.getInstance().getReference("users")

This property provides a reference to the "users" node in the Firebase Realtime Database. It is overridden from the parent class or interface.

Functions

realtimeAdd

override suspend fun realtimeAdd(data: RealtimeRequest): Flow<Resource<Boolean>> =
    callbackFlow {
        setValue(value = data.toMap()) {
            trySend(it)
        }

        awaitClose { this.close() }
    }

This function adds a new entry to the database.

  • Parameters: Takes a RealtimeRequest object.

  • Return Type: Returns a Flow<Resource<Boolean>>.

  • Functionality:

    • Uses callbackFlow to emit database operation results asynchronously.

    • Calls setValue to add the data to the database, converting it to a map using data.toMap().

    • Uses trySend to send the result of the operation.

    • awaitClose ensures the flow is properly closed when no longer needed.

realtimeRemove

override suspend fun realtimeRemove(id: String): Flow<Resource<Boolean>> = callbackFlow {
    removeValue(id = id) {
        trySend(it)
    }

    awaitClose { this.close() }
}

This function removes an entry from the database.

  • Parameters: Takes a String ID.

  • Return Type: Returns a Flow<Resource<Boolean>>.

  • Functionality:

    • Uses callbackFlow to handle asynchronous removal.

    • Calls removeValue to delete the entry with the given ID.

    • Sends the result using trySend.

    • Ensures proper closure with awaitClose.

realtimeList

override suspend fun realtimeList(): Flow<Resource<List<RealtimeResponse>>> = callbackFlow {
    getListValue(
        clazz = RealtimeResponse::class.java,
        eventListener = { trySend(it) }
    )
    awaitClose { this.close() }
}

This function retrieves a list of entries from the database.

  • Parameters: None.

  • Return Type: Returns a Flow<Resource<List<RealtimeResponse>>>.

  • Functionality:

    • Uses callbackFlow to emit the list of entries asynchronously.

    • Calls getListValue to fetch the data and converts it to a list of RealtimeResponse objects.

    • Uses trySend to send the result.

    • Closes the flow with awaitClose.

realtimeEdit

override suspend fun realtimeEdit(id: String): Flow<Resource<Boolean>> = callbackFlow {
    val value = hashMapOf<String, Any?>("name" to "wahid")

    updateValue(id = id, value = value) {
        trySend(it)
    }

    awaitClose(this::close)
}

This function edits an existing entry in the database.

  • Parameters: Takes a String ID.

  • Return Type: Returns a Flow<Resource<Boolean>>.

  • Functionality:

    • Uses callbackFlow for asynchronous editing.

    • Creates a hashMapOf with the field to be updated (name to "wahid").

    • Calls updateValue to update the entry.

    • Sends the result using trySend.

    • Closes the flow with awaitClose.

getData

override suspend fun getData(id: String): Flow<Resource<RealtimeResponse>> = callbackFlow {
    getValue(id = id, clazz = RealtimeResponse::class.java){ data ->
        trySend(data)
    }

    awaitClose(this::close)
}

This function retrieves a specific entry from the database.

  • Parameters: Takes a String ID.

  • Return Type: Returns a Flow<Resource<RealtimeResponse>>.

  • Functionality:

    • Uses callbackFlow for asynchronous data retrieval.

    • Calls getValue to fetch the entry with the given ID and converts it to a RealtimeResponse object.

    • Uses trySend to send the result.

    • Ensures proper closure with awaitClose.

Last updated