23 |
24 |
25 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2021 Rosário Pereira Fernandes
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/.idea/inspectionProfiles/Project_Default.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app"s APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Automatically convert third-party libraries to use AndroidX
19 | android.enableJetifier=true
20 | # Kotlin code style for this project: "official" or "obsolete":
21 | kotlin.code.style=official
--------------------------------------------------------------------------------
/demo/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
14 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/demo/src/main/res/values/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
16 |
17 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/demo/src/main/java/io/github/rosariopfernandes/firebasecompose/ui/theme/Theme.kt:
--------------------------------------------------------------------------------
1 | package io.github.rosariopfernandes.firebasecompose.ui.theme
2 |
3 | import androidx.compose.foundation.isSystemInDarkTheme
4 | import androidx.compose.material.MaterialTheme
5 | import androidx.compose.material.darkColors
6 | import androidx.compose.material.lightColors
7 | import androidx.compose.runtime.Composable
8 |
9 | private val DarkColorPalette = darkColors(
10 | primary = purple200,
11 | primaryVariant = purple700,
12 | secondary = teal200
13 | )
14 |
15 | private val LightColorPalette = lightColors(
16 | primary = purple500,
17 | primaryVariant = purple700,
18 | secondary = teal200
19 |
20 | /* Other default colors to override
21 | background = Color.White,
22 | surface = Color.White,
23 | onPrimary = Color.White,
24 | onSecondary = Color.Black,
25 | onBackground = Color.Black,
26 | onSurface = Color.Black,
27 | */
28 | )
29 |
30 | @Composable
31 | fun FirebaseComposeTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable() () -> Unit) {
32 | val colors = if (darkTheme) {
33 | DarkColorPalette
34 | } else {
35 | LightColorPalette
36 | }
37 |
38 | MaterialTheme(
39 | colors = colors,
40 | typography = typography,
41 | shapes = shapes,
42 | content = content
43 | )
44 | }
--------------------------------------------------------------------------------
/database/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.library'
3 | id 'kotlin-android'
4 | }
5 |
6 | android {
7 | compileSdkVersion 30
8 | buildToolsVersion "30.0.3"
9 |
10 | defaultConfig {
11 | minSdkVersion 21
12 | targetSdkVersion 30
13 | versionCode 1
14 | versionName "1.0.0-beta01"
15 |
16 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
17 | consumerProguardFiles "consumer-rules.pro"
18 | }
19 |
20 | buildTypes {
21 | release {
22 | minifyEnabled false
23 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
24 | }
25 | }
26 | compileOptions {
27 | sourceCompatibility JavaVersion.VERSION_1_8
28 | targetCompatibility JavaVersion.VERSION_1_8
29 | }
30 | kotlinOptions {
31 | jvmTarget = '1.8'
32 | useIR = true
33 | }
34 | buildFeatures {
35 | compose true
36 | }
37 | composeOptions {
38 | kotlinCompilerExtensionVersion compose_version
39 | }
40 | }
41 |
42 | dependencies {
43 |
44 | implementation 'androidx.core:core-ktx:1.3.2'
45 | implementation 'androidx.appcompat:appcompat:1.2.0'
46 | implementation 'com.google.android.material:material:1.3.0'
47 | implementation "androidx.compose.ui:ui:$compose_version"
48 |
49 | api 'com.google.firebase:firebase-database-ktx:19.6.0'
50 |
51 | testImplementation 'junit:junit:4.+'
52 | androidTestImplementation 'androidx.test.ext:junit:1.1.2'
53 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
54 | }
--------------------------------------------------------------------------------
/demo/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
--------------------------------------------------------------------------------
/demo/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.application'
3 | id 'kotlin-android'
4 | id 'com.google.gms.google-services'
5 | }
6 |
7 | android {
8 | compileSdkVersion 30
9 | buildToolsVersion "30.0.3"
10 |
11 | defaultConfig {
12 | applicationId "io.github.rosariopfernandes.firebasecompose"
13 | minSdkVersion 21
14 | targetSdkVersion 30
15 | versionCode 1
16 | versionName "1.0"
17 |
18 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
19 | }
20 |
21 | buildTypes {
22 | release {
23 | minifyEnabled false
24 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
25 | }
26 | }
27 | compileOptions {
28 | sourceCompatibility JavaVersion.VERSION_1_8
29 | targetCompatibility JavaVersion.VERSION_1_8
30 | }
31 | kotlinOptions {
32 | jvmTarget = '1.8'
33 | useIR = true
34 | }
35 | buildFeatures {
36 | compose true
37 | }
38 | composeOptions {
39 | kotlinCompilerExtensionVersion compose_version
40 | }
41 | }
42 |
43 | dependencies {
44 |
45 | implementation 'androidx.core:core-ktx:1.3.2'
46 | implementation 'androidx.appcompat:appcompat:1.2.0'
47 | implementation 'com.google.android.material:material:1.3.0'
48 | implementation "androidx.compose.ui:ui:$compose_version"
49 | implementation "androidx.compose.ui:ui-util:$compose_version"
50 | implementation "androidx.activity:activity-compose:1.3.0-alpha02"
51 | implementation "androidx.compose.material:material:$compose_version"
52 | implementation "androidx.compose.ui:ui-tooling:$compose_version"
53 | implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.3.0'
54 |
55 | // Firebase Compose
56 | implementation project(':firestore')
57 |
58 | // Helper libraries for UI
59 | implementation "dev.chrisbanes.accompanist:accompanist-glide:0.6.0"
60 | implementation "dev.chrisbanes.accompanist:accompanist-insets:0.6.0"
61 |
62 | testImplementation 'junit:junit:4.+'
63 | androidTestImplementation 'androidx.test.ext:junit:1.1.2'
64 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
65 | }
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/firestore/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.library'
3 | id 'kotlin-android'
4 | id 'maven-publish'
5 | }
6 |
7 | android {
8 | compileSdkVersion 30
9 | buildToolsVersion "30.0.3"
10 |
11 | defaultConfig {
12 | minSdkVersion 21
13 | targetSdkVersion 30
14 | versionCode 1
15 | versionName "1.0.0-beta01"
16 |
17 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
18 | consumerProguardFiles "consumer-rules.pro"
19 | }
20 |
21 | buildTypes {
22 | release {
23 | minifyEnabled false
24 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
25 | }
26 | }
27 | compileOptions {
28 | sourceCompatibility JavaVersion.VERSION_1_8
29 | targetCompatibility JavaVersion.VERSION_1_8
30 | }
31 | kotlinOptions {
32 | jvmTarget = '1.8'
33 | useIR = true
34 | }
35 | buildFeatures {
36 | compose true
37 | }
38 | composeOptions {
39 | kotlinCompilerExtensionVersion compose_version
40 | }
41 |
42 | afterEvaluate {
43 | publishing {
44 | publications {
45 | // Creates a Maven publication called "release".
46 | release(MavenPublication) {
47 | // Applies the component for the release build variant.
48 | from components.release
49 |
50 | // You can then customize attributes of the publication as shown below.
51 | groupId = 'com.github.rosariopfernandes'
52 | artifactId = 'firestore'
53 | version = '1.0.0-beta01'
54 | }
55 | // Creates a Maven publication called “debug”.
56 | debug(MavenPublication) {
57 | // Applies the component for the debug build variant.
58 | from components.debug
59 |
60 | groupId = 'com.github.rosariopfernandes'
61 | artifactId = 'firestore-debug'
62 | version = '1.0.0-beta01'
63 | }
64 | }
65 | }
66 |
67 | }
68 | }
69 |
70 | dependencies {
71 |
72 | implementation 'androidx.core:core-ktx:1.3.2'
73 | implementation 'androidx.appcompat:appcompat:1.2.0'
74 | implementation 'com.google.android.material:material:1.3.0'
75 | implementation "androidx.compose.ui:ui:$compose_version"
76 |
77 | api 'com.google.firebase:firebase-firestore-ktx:22.1.0'
78 |
79 | testImplementation 'junit:junit:4.+'
80 | androidTestImplementation 'androidx.test.ext:junit:1.1.2'
81 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
82 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Firebase Compose
2 |
3 | Firebase Compose is an Open Source library for Android that allows you to
4 | quickly connect a Jetpack Compose app to [Firebase](https://firebase.google.com) APIs.
5 |
6 | ## Table of contents
7 |
8 | 1. [Usage](#usage)
9 | 1. [Installation](#installation)
10 | 1. [Dependencies](#dependencies)
11 | 1. [Compatibility](#compatibility-with-firebase-libraries)
12 | 1. [Sample App](#sample-app)
13 | 1. [Contributing](#contributing)
14 | 1. [License](#license)
15 | 1. [Acknowledgment](#acknowledgment)
16 |
17 | ## Usage
18 |
19 | Firebase Compose has separate modules for using Firebase Realtime Database and Cloud Firestore.
20 | To get started, see the individual instructions for each module:
21 |
22 | * [Firebase Compose Firestore](firestore/README.md)
23 | * [Firebase Compose Database](database/README.md)
24 |
25 | ## Installation
26 |
27 | Firebase Compose is published as a collection of libraries separated by the
28 | Firebase API they target. Each Firebase Compose library has a transitive
29 | dependency on the appropriate Firebase SDK so there is no need to include
30 | those separately in your app.
31 |
32 | **Step 1** - Add the jitpack maven in your root `build.gradle` at the end of repositories:
33 | ```gradle
34 | allprojects {
35 | repositories {
36 | ...
37 | maven { url 'https://jitpack.io' }
38 | }
39 | }
40 | ```
41 |
42 | **Step 2** - In your `app/build.gradle` file add a dependency on one of the Firebase Compose
43 | libraries.
44 |
45 | ```groovy
46 | dependencies {
47 | // Firebase Compose for Firebase Realtime Database
48 | implementation 'com.github.rosariopfernandes.firebase-compose:database:1.0.0-beta01'
49 |
50 | // Firebase Compose for Cloud Firestore
51 | implementation 'com.github.rosariopfernandes.firebase-compose:firestore:1.0.0-beta01'
52 | }
53 | ```
54 |
55 | After the project is synchronized, we're ready to start using Firebase functionality in our Compose app.
56 |
57 | ## Dependencies
58 |
59 | ### Compatibility with Firebase libraries
60 |
61 | Firebase Compose libraries have the following transitive dependencies on the Firebase SDK:
62 | ```
63 | firebase-compose:database
64 | |--- com.google.firebase:firebase-database-ktx
65 |
66 | firebase-compose:firestore
67 | |--- com.google.firebase:firebase-firestore-ktx
68 | ```
69 |
70 | ## Sample app
71 | A sample app is available in the [demo](/demo/) directory.
72 |
73 | ## Contributing
74 |
75 | Anyone and everyone is welcome to contribute. Please take a moment to
76 | review the [contributing guidelines](CONTRIBUTING.md).
77 |
78 | ## License
79 |
80 | This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
81 |
82 | ## Acknowledgment
83 | README files inspired by [FirebaseUI](https://github.com/firebase/FirebaseUI-Android/)
84 |
--------------------------------------------------------------------------------
/firestore/src/main/java/io/github/rosariopfernandes/firebasecompose/firestore/DocumentState.kt:
--------------------------------------------------------------------------------
1 | package io.github.rosariopfernandes.firebasecompose.firestore
2 |
3 | import androidx.compose.runtime.getValue
4 | import androidx.compose.runtime.mutableStateOf
5 | import androidx.compose.runtime.setValue
6 | import androidx.compose.runtime.State
7 | import androidx.lifecycle.Lifecycle
8 | import androidx.lifecycle.LifecycleObserver
9 | import androidx.lifecycle.LifecycleOwner
10 | import androidx.lifecycle.OnLifecycleEvent
11 | import com.google.firebase.firestore.DocumentReference
12 | import com.google.firebase.firestore.ListenerRegistration
13 |
14 | /**
15 | * A value holder where reads to the [value] property during the execution of a [Composable]
16 | * function, the current [RecomposeScope] will be subscribed to changes of that value. When the
17 | * [value] property is changed in that Firestore Document, a recomposition of any subscribed
18 | * [RecomposeScope]s will be scheduled.
19 | *
20 | * @see [State]
21 | * @see [documentStateOf]
22 | */
23 | interface DocumentState : State, LifecycleObserver {
24 | override val value: FirestoreDocument
25 | fun startListening()
26 | fun stopListening()
27 | operator fun component1(): FirestoreDocument
28 | }
29 |
30 | /**
31 | * Return a new [DocumentState] initialized with the passed [documentReference]
32 | *
33 | * The DocumentState class is a single value holder whose reads are observed by
34 | * Compose.
35 | *
36 | * @param documentReference the document to be observed
37 | * @param lifecycleOwner the lifecycle owner that the state should react to
38 | *
39 | * @see State
40 | * @see DocumentState
41 | */
42 | fun documentStateOf(
43 | documentReference: DocumentReference,
44 | lifecycleOwner: LifecycleOwner? = null
45 | ) = object : DocumentState {
46 | private var listener: ListenerRegistration? = null
47 | private var snapshotState: FirestoreDocument by mutableStateOf(FirestoreDocument.Loading)
48 |
49 | override val value: FirestoreDocument
50 | get() = snapshotState
51 |
52 | init {
53 | lifecycleOwner?.lifecycle?.addObserver(this)
54 | }
55 |
56 | @OnLifecycleEvent(Lifecycle.Event.ON_START)
57 | override fun startListening() {
58 | if (listener == null) {
59 | listener = documentReference.addSnapshotListener { value, error ->
60 | value?.let { snapshot ->
61 | snapshotState = FirestoreDocument.Snapshot(snapshot)
62 | }
63 | error?.let { exception ->
64 | snapshotState = FirestoreDocument.Error(exception)
65 | }
66 | }
67 | }
68 | }
69 |
70 | @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
71 | override fun stopListening() {
72 | listener?.remove()
73 | }
74 |
75 | override fun component1() = value
76 | }
77 |
78 |
--------------------------------------------------------------------------------
/firestore/src/main/java/io/github/rosariopfernandes/firebasecompose/firestore/CollectionState.kt:
--------------------------------------------------------------------------------
1 | package io.github.rosariopfernandes.firebasecompose.firestore
2 |
3 | import androidx.compose.runtime.getValue
4 | import androidx.compose.runtime.mutableStateOf
5 | import androidx.compose.runtime.setValue
6 | import androidx.compose.runtime.State
7 | import androidx.lifecycle.Lifecycle
8 | import androidx.lifecycle.LifecycleObserver
9 | import androidx.lifecycle.LifecycleOwner
10 | import androidx.lifecycle.OnLifecycleEvent
11 | import com.google.firebase.firestore.ListenerRegistration
12 | import com.google.firebase.firestore.Query
13 |
14 | /**
15 | * A value holder where reads to the [value] property during the execution of a [Composable]
16 | * function, the current [RecomposeScope] will be subscribed to changes of that value. When the
17 | * [value] property is changed in that Firestore Collection, a recomposition of any subscribed
18 | * [RecomposeScope]s will be scheduled.
19 | *
20 | * @see [State]
21 | * @see [collectionStateOf]
22 | */
23 | interface CollectionState : State, LifecycleObserver {
24 | override val value: FirestoreCollection
25 | fun startListening()
26 | fun stopListening()
27 |
28 | operator fun component1(): FirestoreCollection
29 | }
30 |
31 | /**
32 | * Return a new [CollectionState] initialized with the passed [query]
33 | *
34 | * The CollectionState class is a single value holder whose reads are observed by
35 | * Compose.
36 | *
37 | * @param query the collection query to be observed
38 | * @param lifecycleOwner the lifecycle owner that the state should react to
39 | *
40 | * @see State
41 | * @see CollectionState
42 | */
43 | fun collectionStateOf(
44 | query: Query,
45 | lifecycleOwner: LifecycleOwner? = null
46 | ) = object : CollectionState {
47 | private var listener: ListenerRegistration? = null
48 | private var valueState: FirestoreCollection by mutableStateOf(FirestoreCollection.Loading)
49 |
50 | override val value: FirestoreCollection
51 | get() = valueState
52 |
53 | init {
54 | lifecycleOwner?.lifecycle?.addObserver(this)
55 | }
56 |
57 | @OnLifecycleEvent(Lifecycle.Event.ON_START)
58 | override fun startListening() {
59 | if (listener == null) {
60 | listener = query.addSnapshotListener { value, error ->
61 | value?.let { querySnapshot ->
62 | valueState = FirestoreCollection.Snapshot(querySnapshot.documents)
63 | }
64 | error?.let { exception ->
65 | valueState = FirestoreCollection.Error(exception)
66 | }
67 | }
68 | }
69 | }
70 |
71 | @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
72 | override fun stopListening() {
73 | listener?.remove()
74 | }
75 |
76 | override fun component1(): FirestoreCollection = value
77 | }
78 |
79 |
--------------------------------------------------------------------------------
/database/src/main/java/io/github/rosariopfernandes/firebasecompose/database/DatabaseRefState.kt:
--------------------------------------------------------------------------------
1 | package io.github.rosariopfernandes.firebasecompose.database
2 |
3 | import androidx.compose.runtime.State
4 | import androidx.compose.runtime.getValue
5 | import androidx.compose.runtime.mutableStateOf
6 | import androidx.compose.runtime.setValue
7 | import androidx.lifecycle.Lifecycle
8 | import androidx.lifecycle.LifecycleObserver
9 | import androidx.lifecycle.LifecycleOwner
10 | import androidx.lifecycle.OnLifecycleEvent
11 | import com.google.firebase.database.DataSnapshot
12 | import com.google.firebase.database.DatabaseError
13 | import com.google.firebase.database.DatabaseReference
14 | import com.google.firebase.database.ValueEventListener
15 |
16 | /**
17 | * A value holder where reads to the [value] property during the execution of a
18 | * [androidx.compose.runtime.Composable] function, the current
19 | * [androidx.compose.runtime.RecomposeScope] will be subscribed to changes of that value. When the
20 | * [value] property is changed in that Database Reference, a recomposition of any subscribed
21 | * [androidx.compose.runtime.RecomposeScope]s will be scheduled.
22 | *
23 | * @see [State]
24 | * @see [databaseRefStateOf]
25 | */
26 | interface DatabaseRefState : State, LifecycleObserver {
27 | override val value: RTDBData
28 | fun startListening()
29 | fun stopListening()
30 | operator fun component1(): RTDBData
31 | }
32 |
33 | /**
34 | * Return a new [DatabaseRefState] initialized with the passed [databaseRef]
35 | *
36 | * The DatabaseRefState class is a single value holder whose reads are observed by
37 | * Compose.
38 | *
39 | * @param databaseRef the database reference to be observed
40 | * @param lifecycleOwner the lifecycle owner that the state should react to
41 | *
42 | * @see State
43 | * @see DatabaseRefState
44 | */
45 | fun databaseRefStateOf(
46 | databaseRef: DatabaseReference,
47 | lifecycleOwner: LifecycleOwner? = null
48 | ) = object : DatabaseRefState {
49 | private var listener: ValueEventListener? = null
50 | private var dataState: RTDBData by mutableStateOf(RTDBData.Loading)
51 |
52 | override val value: RTDBData
53 | get() = dataState
54 |
55 | init {
56 | lifecycleOwner?.lifecycle?.addObserver(this)
57 | }
58 |
59 | @OnLifecycleEvent(Lifecycle.Event.ON_START)
60 | override fun startListening() {
61 | if (listener == null) {
62 | listener = databaseRef.addValueEventListener(object : ValueEventListener {
63 | override fun onDataChange(snapshot: DataSnapshot) {
64 | dataState = RTDBData.Snapshot(snapshot)
65 | }
66 |
67 | override fun onCancelled(error: DatabaseError) {
68 | dataState = RTDBData.Error(error)
69 | }
70 | })
71 | }
72 | }
73 |
74 | @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
75 | override fun stopListening() {
76 | listener?.let { databaseRef.removeEventListener(it) }
77 | }
78 |
79 | override fun component1() = value
80 | }
81 |
--------------------------------------------------------------------------------
/database/src/main/java/io/github/rosariopfernandes/firebasecompose/database/DatabaseListRefState.kt:
--------------------------------------------------------------------------------
1 | package io.github.rosariopfernandes.firebasecompose.database
2 |
3 | import androidx.compose.runtime.State
4 | import androidx.compose.runtime.getValue
5 | import androidx.compose.runtime.mutableStateOf
6 | import androidx.compose.runtime.setValue
7 | import androidx.lifecycle.Lifecycle
8 | import androidx.lifecycle.LifecycleObserver
9 | import androidx.lifecycle.LifecycleOwner
10 | import androidx.lifecycle.OnLifecycleEvent
11 | import com.google.firebase.database.DataSnapshot
12 | import com.google.firebase.database.DatabaseError
13 | import com.google.firebase.database.DatabaseReference
14 | import com.google.firebase.database.ValueEventListener
15 |
16 | /**
17 | * A value holder where reads to the [value] property during the execution of a
18 | * [androidx.compose.runtime.Composable] function, the current
19 | * [androidx.compose.runtime.RecomposeScope] will be subscribed to changes
20 | * of that value. When the [value] property is changed in that Database Reference,
21 | * a recomposition of any subscribed [androidx.compose.runtime.RecomposeScope]s
22 | * will be scheduled.
23 | *
24 | * @see [State]
25 | * @see [databaseListRefStateOf]
26 | */
27 | interface DatabaseListRefState : State, LifecycleObserver {
28 | override val value: RTDBDataList
29 | fun startListening()
30 | fun stopListening()
31 | operator fun component1(): RTDBDataList
32 | }
33 |
34 | /**
35 | * Return a new [DatabaseListRefState] initialized with the passed [databaseRef]
36 | *
37 | * The DatabaseListRefState class is a single value holder whose reads are observed by
38 | * Compose.
39 | *
40 | * @param databaseRef the database reference whose children will be observed
41 | * @param lifecycleOwner the lifecycle owner that the state should react to
42 | *
43 | * @see State
44 | * @see DatabaseRefState
45 | */
46 | fun databaseListRefStateOf(
47 | databaseRef: DatabaseReference,
48 | lifecycleOwner: LifecycleOwner? = null
49 | ) = object : DatabaseListRefState {
50 | private var listener: ValueEventListener? = null
51 | private var dataState: RTDBDataList by mutableStateOf(RTDBDataList.Loading)
52 |
53 | override val value: RTDBDataList
54 | get() = dataState
55 |
56 | init {
57 | lifecycleOwner?.lifecycle?.addObserver(this)
58 | }
59 |
60 | @OnLifecycleEvent(Lifecycle.Event.ON_START)
61 | override fun startListening() {
62 | if (listener == null) {
63 | listener = databaseRef.addValueEventListener(object : ValueEventListener {
64 | override fun onDataChange(snapshot: DataSnapshot) {
65 | val list = snapshot.children.toList()
66 | dataState = RTDBDataList.SnapshotList(list)
67 | }
68 |
69 | override fun onCancelled(error: DatabaseError) {
70 | dataState = RTDBDataList.Error(error)
71 | }
72 | })
73 | }
74 | }
75 |
76 | @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
77 | override fun stopListening() {
78 | listener?.let { databaseRef.removeEventListener(it) }
79 | }
80 |
81 | override fun component1() = value
82 | }
83 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing Guidelines
2 |
3 | We love contributions! But we'd like you to follow these guidelines to make the contribution process
4 | easy for everyone involved:
5 |
6 | ## Issue Tracker
7 |
8 | The issue tracker is our main channel to report a bug in the source code or a mistake in the
9 | documentation, and to request a new feature.
10 |
11 | Before submitting your issue, please search the archive. Maybe your question was already answered,
12 | your bug has already been reported or your feature has already been requested.
13 |
14 | Providing the following information will increase the chances of your issue being dealt with
15 | quickly:
16 |
17 | * **Bug reports** - if an error is being thrown, please include a stack trace and the steps to
18 | reproduce the error. If there is no error, please explain why do you consider it a bug.
19 |
20 | * **Feature Requests** - please make it clear whether you're willing to write the code for it or you
21 | need someone else to do it.
22 |
23 | * **Related Issues** - if you found a similar issue that has been reported before, be sure to
24 | mention it.
25 |
26 | ## Pull Requests
27 |
28 | Before making any changes, consider following these steps:
29 |
30 | 1. Search for an open or closed Pull Request related to your changes.
31 |
32 | 2. Search the issue tracker for issues related to your changes.
33 |
34 | 3. Open a [new issue](github.com/rosariopfernandes/FirebaseCompose/issues/new) to discuss your changes
35 | with the project owners. If they approve it, send the Pull Request.
36 |
37 | ### Sending Pull Requests
38 | If your change has been approved, follow this process:
39 |
40 | 1. [Fork](http://help.github.com/fork-a-repo/) the project, clone your fork and configure the
41 | remotes:
42 |
43 | ```bash
44 | # Clone your fork into the current directory
45 | git clone https://github.com//
46 | # Navigate to the newly cloned directory
47 | cd
48 | # Assign the original repo to a remote called "upstream"
49 | git remote add upstream https://github.com/rosariopfernandes/FirebaseCompose
50 | ```
51 |
52 | 2. Make your changes in a new branch:
53 |
54 | ```bash
55 | git checkout -b my-fix-branch master
56 | ```
57 |
58 | 3. Commit the changes using a descriptive commit message
59 |
60 | ```bash
61 | git commit -a
62 | ```
63 |
64 | Note: the optional commit `-a` command line option will automatically "add" and "rm" edited files.
65 |
66 | 4. Push your branch to GitHub:
67 |
68 | ```bash
69 | git push origin my-fix-branch
70 | ```
71 |
72 | 5. In GitHub, [send a Pull Request](https://help.github.com/articles/using-pull-requests/) with a
73 | clear title and description.
74 |
75 | * If we suggest changes then:
76 | * Make the required changes;
77 | * Rebase your branch and force push to your GitHub repository (this updates your Pull Request):
78 | ```bash
79 | # Rebase the branch
80 | git rebase master -i
81 | # Update the Pull Request
82 | git push origin my-fix-branch -f
83 | ```
84 | That's it! Thank you for you contribution!
85 |
86 | ### After your Pull Request is merged
87 |
88 | You can delete your branch and pull changes from the original
89 | (upstream) repository:
90 |
91 | 1. Delete the remote branch on GitHub either through the GitHub UI or your local shell as follows:
92 |
93 | ```bash
94 | git push origin --delete my-fix-branch
95 | ```
96 |
97 | 2. Check out the master branch:
98 |
99 | ```bash
100 | git checkout master -f
101 | ```
102 |
103 | 3. Delete the local branch:
104 |
105 | ```bash
106 | git branch -D my-fix-branch
107 | ```
108 |
109 | 4. Update your master with the latest upstream version:
110 |
111 | ```bash
112 | git pull --ff upstream master
113 | ```
114 |
115 | ## Coding Rules
116 |
117 | We generally follow the
118 | [Android Kotlin Style Guide](https://android.github.io/kotlin-guides/style.html).
119 |
--------------------------------------------------------------------------------
/.idea/codeStyles/Project.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |