• Stars
    star
    224
  • Rank 177,792 (Top 4 %)
  • Language
    Swift
  • License
    MIT License
  • Created over 6 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

RxSwift extensions for Firebase

RxFirebase

CI Status Version License Platform

Requirements

Xcode 9.0

Swift 4.0

Installation

RxFirebase is available through CocoaPods. To install it, simply add the following lines to your Podfile:

pod 'RxFirebase/Firestore'
pod 'RxFirebase/RemoteConfig'
pod 'RxFirebase/Database'
pod 'RxFirebase/Storage'
pod 'RxFirebase/Auth'
pod 'RxFirebase/Functions'

Usage

import RxFirebase

Database

Basic write operation:

let ref = Database.database().reference()

ref.child("users")
    .child("1")
    .rx
    .setValue(["username": "Arnonymous"])
    .subscribe(onNext: { _ in
        print("Document successfully updated")
    }).disposed(by: disposeBag)
    
// https://firebase.google.com/docs/database/ios/read-and-write#basic_write

Listen for value events:

let ref = Database.database().reference()

ref.child("users")
    .child("1")
    .rx
    .observeEvent(.value)
    .subscribe(onNext: { snapshot in
        print("Value:\(snapshot.value)")
    }).disposed(by: disposeBag)
    
// https://firebase.google.com/docs/database/ios/read-and-write#listen_for_value_events

Read data once:

let ref = Database.database().reference()

ref.child("users")
    .child("1")
    .rx
    .observeSingleEvent(.value)
    .subscribe(onNext: { snapshot in
        print("Value:\(snapshot.value)")
    }).disposed(by: disposeBag)
    
// https://firebase.google.com/docs/database/ios/read-and-write#read_data_once

Update specific fields:

let ref = Database.database().reference()

let childUpdates = ["/posts/\(key)": post,
                    "/user-posts/\(userID)/\(key)/": post]
ref.rx.updateChildValues(childUpdates)
    .subscribe(onNext: { _ in
        // Success
    }).disposed(by: disposeBag)

// https://firebase.google.com/docs/database/ios/read-and-write#update_specific_fields

Delete data:

let ref = Database.database().reference()

ref.rx.removeValue()
    .subscribe(onNext: { _ in
        // Success
    }).disposed(by: disposeBag)
    
// https://firebase.google.com/docs/database/ios/read-and-write#delete_data

Save data as transactions

let ref = Database.database().reference()

ref.rx.runTransactionBlock { currentData in
        // TransactionResult
    }.subscribe(onNext: { _ in
        // Success
    }).disposed(by: disposeBag)
    
// https://firebase.google.com/docs/database/ios/read-and-write#save_data_as_transactions

Firestore

Setting data:

let db = Firestore.firestore()

// Add a new document in collection "cities"
db.collection("cities")
    .document("SF")
    .rx
    .setData([
        "name": "San Francisco",
        "state": "CA",
        "country": "USA",
        "capital": false,
        "population": 860000
        ]).subscribe(onError: { error in
            print("Error setting data: \(error)")
        }).disposed(by: disposeBag)
       
// Add a new document with a generated id.
db.collection("cities")
    .rx
    .addDocument(data: [
        "name": "San Francisco",
        "state": "CA",
        "country": "USA",
        "capital": false,
        "population": 860000
        ]).subscribe(onNext: { ref in
            print("Document added with ID: \(ref.documentID)")
        }, onError: { error in
            print("Error adding document: \(error)")
        }).disposed(by: disposeBag)
        
// Set the "capital" field of the city 'SF'
db.collection("cities")
    .document("SF")
    .rx
    .updateData([
        "capital": true
        ]).subscribe(onNext: {
            print("Document successfully updated")
        }, onError: { error in
            print("Error updating document: \(error)")
        }).disposed(by: disposeBag)
        
// https://firebase.google.com/docs/firestore/manage-data/add-data

Get a document:

let db = Firestore.firestore()

db.collection("cities")
    .document("SF")
    .rx
    .getDocument()
    .subscribe(onNext: { document in
        if let document = document {
            print("Document data: \(document.data())")
        } else {
            print("Document does not exist")
        }
    }, onError: { error in
        print("Error fetching snapshots: \(error)")
    }).disposed(by: disposeBag)
    
// https://firebase.google.com/docs/firestore/query-data/get-data

Get Realtime Updates:

let db = Firestore.firestore()

// Document
db.collection("cities")
    .document("SF")
    .rx
    .listen()
    .subscribe(onNext: { document in
        print("Current data: \(document.data())")
    }, onError: { error in
        print("Error fetching snapshots: \(error)")
    }).disposed(by: disposeBag)
    
// Collection
db.collection("cities")
    .rx
    .listen()
    .subscribe(onNext: { snapshot in
        snapshot.documentChanges.forEach { diff in
            if (diff.type == .added) {
                print("New city: \(diff.document.data())")
            }
            if (diff.type == .modified) {
                print("Modified city: \(diff.document.data())")
            }
            if (diff.type == .removed) {
                print("Removed city: \(diff.document.data())")
            }
        }
    }, onError: { error in
        print("Error fetching snapshots: \(error)")
    }).disposed(by: disposeBag)

// https://firebase.google.com/docs/firestore/query-data/listen

Batched writes:

let db = Firestore.firestore()

// Get new write batch
let batch = db.batch()

// Update the population of 'SF'
let sfRef = db.collection("cities").document("SF")
batch.updateData(["population": 1000000 ], forDocument: sfRef)

// Commit the batch
batch.rx
    .commit()
    .subscribe(onNext: {
        print("Batch write succeeded.")
    }, onError: { error in
        print("Error writing batch \(error)")
    }).disposed(by: disposeBag)
    
// https://firebase.google.com/docs/firestore/manage-data/transactions

Transactions:

let db = Firestore.firestore()
let sfReference = db.collection("cities").document("SF")

db.rx.runTransaction { transaction in
    let sfDocument = try transaction.getDocument(sfReference)
    
    guard let oldPopulation = sfDocument.data()?["population"] as? Int else {
        let error = NSError(
            domain: "AppErrorDomain",
            code: -1,
            userInfo: [
                NSLocalizedDescriptionKey: "Unable to retrieve population from snapshot \(sfDocument)"
            ]
        )
        throw error
    }
    
    transaction.updateData(["population": oldPopulation + 1], forDocument: sfReference)
    return nil
    }.subscribe(onNext: { _ in
        print("Transaction successfully committed!")
    }, onError: { error in
        print("Transaction failed: \(error)")
    }).disposed(by: disposeBag)
    
    // https://firebase.google.com/docs/firestore/manage-data/transactions

RemoteConfig

Fetch:

// TimeInterval is set to expirationDuration here, indicating the next fetch request will use
// data fetched from the Remote Config service, rather than cached parameter values, if cached
// parameter values are more than expirationDuration seconds old. See Best Practices in the
// README for more information.
RemoteConfig.remoteConfig()
    .rx
    .fetch(withExpirationDuration: TimeInterval(expirationDuration), activateFetched: true)
    .subscribe(onNext: { status in
        print("Config fetched! with success:\(status == .success)")
    }, onError: { error in
        print("Error: \(error)")
    }).disposed(by: disposeBag)

    // https://firebase.google.com/docs/remote-config/ios

Storage

Upload:

let reference = Storage.storage()
    .reference(forURL: "\(your_firebase_storage_bucket)/images/space.jpg")
    .rx
    
let data: Data // Upload data
reference.putData(data)
    .subscribe(onNext: { metadata in
        // Success
    }, onError: { error in
        // Uh-oh, an error occurred!
    }).disposed(by: disposeBag)
    

let fileURL: URL // Upload file
reference.putFile(from: fileURL)
    .subscribe(onNext: { metadata in
        // Success
    }, onError: { error in
        // Uh-oh, an error occurred!
    }).disposed(by: disposeBag)

Observe events:

let reference = Storage.storage()
    .reference(forURL: "\(your_firebase_storage_bucket)/images/space.jpg")
    .rx

let fileURL: URL // Upload file
let uploadTask = reference.putFile(from: fileURL)

// Listen for state changes
uploadTask.rx.observe(.progress)
    .subscribe(onNext: { snapshot in
        // Upload reported progress
        let percentComplete = 100.0 * Double(snapshot.progress!.completedUnitCount)
        / Double(snapshot.progress!.totalUnitCount)
    }, onError: { error in
        // Uh-oh, an error occurred!
    }).disposed(by: disposeBag)

Download:

let reference = Storage.storage()
    .reference(forURL: "\(your_firebase_storage_bucket)/images/space.jpg")
    .rx

// Download in memory with a maximum allowed size of 1MB (1 * 1024 * 1024 bytes)
reference.getData(maxSize: 1 * 1024 * 1024)
    .subscribe(onNext: { data in
        // Data for "images/space.jpg" is returned
    }, onError: { error in
        // Uh-oh, an error occurred!
    }).disposed(by: disposeBag)
    
    
    
// Create local filesystem URL
let localURL = URL(string: "path/to/image")!
    
// Download to the local filesystem
reference.write(toFile: localURL)
    .subscribe(onNext: { data in
        // Local file URL for "images/space.jpg" is returned
    }, onError: { error in
        // Uh-oh, an error occurred!
    }).disposed(by: disposeBag)

URL:

let reference = Storage.storage()
    .reference(forURL: "\(your_firebase_storage_bucket)/images/space.jpg")
    .rx
    
// Fetch the download URL
reference.downloadURL()
    .subscribe(onNext: { url in
        // Get the download URL for 'images/space.jpg'
    }, onError: { error in
        // Handle any errors
    }).disposed(by: disposeBag)

Metadata:

let reference = Storage.storage()
    .reference(forURL: "\(your_firebase_storage_bucket)/images/space.jpg")
    .rx
    
// Create file metadata to update
let newMetadata = StorageMetadata()
    
// Update metadata properties
reference.updateMetadata(newMetadata)
    .subscribe(onNext: { metadata in
        // Updated metadata for 'images/space.jpg' is returned
    }, onError: { error in
        // Uh-oh, an error occurred!
    }).disposed(by: disposeBag)
    
    
// Get metadata properties
reference.getMetadata()
    .subscribe(onNext: { metadata in
        // Metadata now contains the metadata for 'images/space.jpg'
    }, onError: { error in
        // Uh-oh, an error occurred!
    }).disposed(by: disposeBag)

Delete:

let reference = Storage.storage()
    .reference(forURL: "\(your_firebase_storage_bucket)/images/space.jpg")
    .rx
    
// Delete the file
reference.delete()
    .subscribe(onNext: {
        // File deleted successfully
    }, onError: { error in
        // Uh-oh, an error occurred!
    }).disposed(by: disposeBag)

Auth

Create:

let auth = Auth.auth()
    
// Create a password-based account
auth.rx.createUser(withEmail: "[email protected]", password: "1q2w3e4r")
    .subscribe(onNext: { authResult in
        // User signed in
    }, onError: { error in
        // Uh-oh, an error occurred!
    }).disposed(by: disposeBag)

// https://firebase.google.com/docs/auth/ios/password-auth

Sign In:

let auth = Auth.auth()
    
// Sign in a user with an email address and password
auth.rx.signIn(withEmail: "[email protected]", password: "1q2w3e4r")
    .subscribe(onNext: { authResult in
        // User signed in
    }, onError: { error in
        // Uh-oh, an error occurred!
    }).disposed(by: disposeBag)

// https://firebase.google.com/docs/auth/ios/password-auth

User

Update Email:

let user = Auth.auth().currentUser?
    
// Set a user's email address
user.rx.updateEmail(to: "[email protected]")
    .subscribe(onNext: {
        // Completed updating Email
    }, onError: { error in
        // Uh-oh, an error occurred!
    }).disposed(by: disposeBag)

// https://firebase.google.com/docs/auth/ios/manage-users

Delete:

let user = Auth.auth().currentUser?

// Delete a user
user.rx.delete()
    .subscribe(onNext: {
        // User deleted
    }, onError: { error in
        // Uh-oh, an error occurred!
    }).disposed(by: disposeBag)

// https://firebase.google.com/docs/auth/ios/manage-users

Functions

let functions = Functions.functions()
let request = functions.httpsCallable("functionName").rx

request
    .call(["parameter": "value"])
    .subscribe(onNext: { result in
        print("response:\(result)")
    }, onError: { error in
        print("error:\(error)")
    }).disposed(by: disposeBag)
    
    // https://firebase.google.com/docs/functions/callable#call_the_function

License

This library belongs to RxSwiftCommunity.

RxFirebase is available under the MIT license. See the LICENSE file for more info.

More Repositories

1

RxDataSources

UITableView and UICollectionView Data Sources for RxSwift (sections, animated updates, editing ...)
Swift
3,054
star
2

RxFlow

RxFlow is a navigation framework for iOS applications based on a Reactive Flow Coordinator pattern
Swift
1,872
star
3

RxAlamofire

RxSwift wrapper around the elegant HTTP networking in Swift Alamofire
Swift
1,612
star
4

RxKeyboard

Reactive Keyboard in iOS
Swift
1,533
star
5

RxGesture

RxSwift reactive wrapper for view gestures
Swift
1,369
star
6

RxSwiftExt

A collection of Rx operators & tools not found in the core RxSwift distribution
Swift
1,317
star
7

RxRealm

RxSwift extension for RealmSwift's types
Swift
1,153
star
8

Action

Abstracts actions to be performed in RxSwift.
Swift
875
star
9

RxOptional

RxSwift extensions for Swift optionals and "Occupiable" types
Swift
701
star
10

RxAnimated

Animated RxCocoa bindings
Swift
686
star
11

NSObject-Rx

Handy RxSwift extensions on NSObject, including rx.disposeBag.
Swift
640
star
12

RxMarbles

RxMarbles iOS app
Swift
482
star
13

RxViewModel

ReactiveViewModel-esque using RxSwift
Swift
401
star
14

RxTheme

Theme management based on Rx
Swift
381
star
15

RxReachability

RxSwift bindings for Reachability
Swift
283
star
16

RxNimble

Nimble extensions making unit testing with RxSwift easier πŸŽ‰
Swift
265
star
17

RxWebKit

RxWebKit is a RxSwift wrapper for WebKit
Swift
248
star
18

RxKingfisher

Reactive extension for the Kingfisher image downloading and caching library
Swift
223
star
19

RxGRDB

Reactive extensions for SQLite
Swift
218
star
20

RxSwiftUtilities

Helpful classes and extensions for RxSwift
Swift
189
star
21

RxCoreLocation

RxCoreLocation is a reactive abstraction to manage Core Location.
Swift
181
star
22

RxMediaPicker

A reactive wrapper built around UIImagePickerController.
Swift
179
star
23

RxCoreData

RxSwift extensions for Core Data
C
164
star
24

RxRealmDataSources

An easy way to bind an RxRealm observable to a table or collection view
Swift
161
star
25

RxState

Redux implementation in Swift using RxSwift
Swift
153
star
26

RxStarscream

A lightweight extension to subscribe Starscream websocket events with RxSwift
Swift
152
star
27

RxVisualDebugger

WIP! Very quick and very dirty test for a visual Rx debugger
JavaScript
142
star
28

RxLocalizer

RxLocalizer allows you to localize your apps, using RxSwift πŸš€
Swift
134
star
29

RxBiBinding

Reactive two-way binding
Swift
126
star
30

RxReduce

RxReduce is a lightweight framework that ease the implementation of a state container pattern in a Reactive Programming compliant way.
Swift
125
star
31

RxMKMapView

RxMKMapView is a RxSwift wrapper for MKMapView `delegate`.
Swift
121
star
32

RxASDataSources

RxDataSource for AsyncDisplayKit/Texture
Swift
119
star
33

RxCocoa-Texture

RxCocoa Extension Library for Texture.
Swift
100
star
34

RxGoogleMaps

RxSwift reactive wrapper for GoogleMaps SDK
Swift
95
star
35

RxSegue

Swift
80
star
36

FirebaseRxSwiftExtensions

Extension Methods for Firebase and RxSwift
Swift
77
star
37

RxMultipeer

A testable RxSwift wrapper around MultipeerConnectivity
Swift
69
star
38

RxIGListKit

RxSwift wrapper for IGListKit
Swift
62
star
39

RxBinding

Simple data binding operators ~> and <~> for RxSwift.
Swift
62
star
40

RxPager

Pager for RxSwift
Swift
60
star
41

RxCoreMotion

Provides an easy and straight-forward way to use Apple iOS CoreMotion responses as Rx Observables.
Swift
60
star
42

RxFileMonitor

RxSwift wrapper around CoreFoundation file events (FSEvent*)
Swift
60
star
43

RxFirebase-Deprecated

Implement RxSwift with the new Firebase
Swift
54
star
44

RxAlert

Swift
50
star
45

RxSnippets

Several snippets for work with RxSwift
50
star
46

RxCookbook

Community driven RxSwift cookbook πŸ΄πŸ“š
50
star
47

rxswiftcommunity.github.io

For projects that support RxSwift
Ruby
50
star
48

RxController

A library for developing iOS app with MVVM-C based on RxFlow and RxSwift.
Swift
42
star
49

RxHttpClient

Simple Http client (Use RxSwift for stream data)
Swift
39
star
50

RxEventHub

`RxEventHub` makes multicasting event easy, type-safe and error-free, use it instead of `NSNotificationCenter` now!
Swift
36
star
51

RxModal

Subscribe to your modal flows
Swift
28
star
52

RxBatteryManager

A Reactive BatteryManager in Swift for iOS
Swift
24
star
53

RxAlertViewable

A simple alert library with RxSwift MVVM supported.
Swift
20
star
54

contributors

Guidelines for contributing to the RxSwiftCommunity, and a good place to raise questions.
20
star
55

guides.rxswift.org

Content of the website guides.rxswift.org
HTML
19
star
56

RxAVFoundation

RxAVFoundation (based on RxSwift)
Swift
17
star
57

RxTask

An RxSwift implementation of a command line runner.
Swift
15
star
58

RxContacts

RxContacts is a RxSwift wrapper around the Contacts Framework.
Swift
13
star
59

RxTestExt

A collection of operators & tools not found in the core RxTest distribution
Swift
13
star
60

RxVision

RxVision (based on RxSwift)
Swift
13
star
61

RxCoreNFC

RxCoreNFC (based on RxSwift)
Swift
11
star
62

RxCloudKit

RxCloudKit (based on RxSwift)
Swift
9
star
63

RxARKit

RxARKit (based on RxSwift)
Swift
9
star
64

RxTapAction

Reactive extensions for adding tap action gesture to UIView or UICollectionView.
Swift
9
star
65

RxSceneKit

RxSceneKit (based on RxSwift)
Swift
5
star
66

SimplestDemostrationOfUsingOperator

Simplest way to show how `using` operator works.
Swift
5
star
67

Docs

RxSwift Official Docs - Generated by Jazzy
HTML
5
star
68

RxSocket.io

Rx wrapper over socket.io library with Generic functions
Swift
5
star
69

RxSpriteKit

RxSpriteKit (based on RxSwift)
Swift
4
star
70

RxOnDemandResources

RxOnDemandResources (based on RxSwift)
Swift
4
star
71

FakeRepo

This is a temporary fake repo, please ignore it :)
Swift
2
star
72

peril

Settings for the RxSwiftCommunity organization's Peril server
TypeScript
2
star