RxSwiftCommunity/RxFirebase

Name: RxFirebase

Owner: RxSwift Community

Description: RxSwift extensions for Firebase

Created: 2018-03-31 13:43:40.0

Updated: 2018-05-24 04:00:12.0

Pushed: 2018-05-16 13:34:37.0

Homepage: null

Size: 104

Language: Swift

GitHub Committers

UserMost Recent Commit# Commits

Other Committers

UserEmailMost Recent Commit# Commits

README

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 line to your Podfile:

'RxFirebase/Firestore'
'RxFirebase/RemoteConfig'
'RxFirebase/Database'
Usage
rt RxFirebase
Database

Basic write operation:

ref = Database.database().reference()

child("users")
.child("1")
.rx
.setValue(["username": "Arnonymous"])
.subscribe(onNext: { _ in
    print("Document successfully updated")
}).disposed(by: disposeBag)

ttps://firebase.google.com/docs/database/ios/read-and-write#basic_write

Listen for value events:

ref = Database.database().reference()

child("users")
.child("1")
.rx
.observeEvent(.value)
.subscribe(onNext: { snapshot in
    print("Value:\(snapshot.value)")
}).disposed(by: disposeBag)

ttps://firebase.google.com/docs/database/ios/read-and-write#listen_for_value_events

Read data once:

ref = Database.database().reference()

child("users")
.child("1")
.rx
.observeSingleEvent(.value)
.subscribe(onNext: { snapshot in
    print("Value:\(snapshot.value)")
}).disposed(by: disposeBag)

ttps://firebase.google.com/docs/database/ios/read-and-write#read_data_once

Update specific fields:

ref = Database.database().reference()

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

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

Delete data:

ref = Database.database().reference()

rx.removeValue()
.subscribe(onNext: { _ in
    // Success
}).disposed(by: disposeBag)

ttps://firebase.google.com/docs/database/ios/read-and-write#delete_data

Save data as transactions

ref = Database.database().reference()

rx.runTransactionBlock { currentData in
    // TransactionResult
}.subscribe(onNext: { _ in
    // Success
}).disposed(by: disposeBag)

ttps://firebase.google.com/docs/database/ios/read-and-write#save_data_as_transactions
Firestore

Setting data:

db = Firestore.firestore()

dd a new document in collection "cities"
ollection("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)

dd a new document with a generated id.
ollection("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)

et the "capital" field of the city 'SF'
ollection("cities")
.document("SF")
.rx
.updateData([
    "capital": true
    ]).subscribe(onNext: {
        print("Document successfully updated")
    }, onError: { error in
        print("Error updating document: \(error)")
    }).disposed(by: disposeBag)

ttps://firebase.google.com/docs/firestore/manage-data/add-data

Get a document:

db = Firestore.firestore()

ollection("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)

ttps://firebase.google.com/docs/firestore/query-data/get-data

Get Realtime Updates:

db = Firestore.firestore()

ocument
ollection("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)

ollection
ollection("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)

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

Batched writes:

db = Firestore.firestore()

et new write batch
batch = db.batch()

pdate the population of 'SF'
sfRef = db.collection("cities").document("SF")
h.updateData(["population": 1000000 ], forDocument: sfRef)

ommit the batch
h.rx
.commit()
.subscribe(onNext: {
    print("Batch write succeeded.")
}, onError: { error in
    print("Error writing batch \(error)")
}).disposed(by: disposeBag)

ttps://firebase.google.com/docs/firestore/manage-data/transactions

Transactions:

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

x.runTransaction { transaction, errorPointer in
let sfDocument: DocumentSnapshot
do {
    try sfDocument = transaction.getDocument(sfReference)
} catch let fetchError as NSError {
    errorPointer?.pointee = fetchError
    return nil
}

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)"
        ]
    )
    errorPointer?.pointee = error
    return nil
}

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:

imeInterval is set to expirationDuration here, indicating the next fetch request will use
ata fetched from the Remote Config service, rather than cached parameter values, if cached
arameter values are more than expirationDuration seconds old. See Best Practices in the
EADME for more information.
teConfig.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
License

This library belongs to RxSwiftCommunity.

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


This work is supported by the National Institutes of Health's National Center for Advancing Translational Sciences, Grant Number U24TR002306. This work is solely the responsibility of the creators and does not necessarily represent the official views of the National Institutes of Health.