RxSwiftCommunity/RxRealm

Name: RxRealm

Owner: RxSwift Community

Description: RxSwift extension for RealmSwift's types

Created: 2016-04-19 10:53:02.0

Updated: 2018-01-18 13:07:31.0

Pushed: 2017-12-08 01:50:50.0

Homepage:

Size: 21572

Language: Swift

GitHub Committers

UserMost Recent Commit# Commits

Other Committers

UserEmailMost Recent Commit# Commits

README

RxRealm

Carthage Compatible Version License Platform

This library is a thin wrapper around RealmSwift ( Realm Docs ).

Table of contents:

  1. Observing object collections
  2. Observing a single object
  3. Write transactions
  4. Automatically binding table and collection views
  5. Example app
Observing object collections

RxRealm can be used to create Observables from objects of type Results, List, LinkingObjects or AnyRealmCollection. These types are typically used to load and observe object collections from the Realm Mobile Database.

Observable.collection(from:synchronousStart:)

Emits an event each time the collection changes:

realm = try! Realm()
laps = realm.objects(Lap.self)

rvable.collection(from: laps)
ap { 
laps in "\(laps.count) laps"

ubscribe(onNext: { text  in
print(text)

The above prints out “X laps” each time a lap is added or removed from the database. If you set synchronousStart to true (the default value), the first element will be emitted synchronously - e.g. when you're binding UI it might not be possible for an asynchronous notification to come through.

Observable.array(from:synchronousStart:)

Upon each change fetches a snapshot of the Realm collection and converts it to an array value (for example if you want to use array methods on the collection):

realm = try! Realm()
laps = realm.objects(Lap.self)

rvable.array(from: laps)
ap { array in
return array.prefix(3) //slice of first 3 items

ubscribe(onNext: { text  in
print(text)

Observable.changeset(from:synchronousStart:)

Emits every time the collection changes and provides the exact indexes that has been deleted, inserted or updated:

realm = try! Realm()
laps = realm.objects(Lap.self)

rvable.changeset(from: laps)
ubscribe(onNext: { results, changes in
if let changes = changes {
  // it's an update
  print(results)
  print("deleted: \(changes.deleted)")
  print("inserted: \(changes.inserted)")
  print("updated: \(changes.updated)")
} else {
  // it's the initial data
  print(results)
}

Observable.arrayWithChangeset(from:synchronousStart:)

Combines the result of Observable.array(from:) and Observable.changeset(from:) returning an Observable<Array<T>, RealmChangeset?>

realm = try! Realm()
laps = realm.objects(Lap.self))

rvable.arrayWithChangeset(from: laps)
ubscribe(onNext: { array, changes in
if let changes = changes {
// it's an update
print(array.first)
print("deleted: \(changes.deleted)")
print("inserted: \(changes.inserted)")
print("updated: \(changes.updated)")
else {
// it's the initial data
print(array)


Observing a single object

There's a separate API to make it easier to observe a single object:

rvable.from(object: ticker)
.map { ticker -> String in
    return "\(ticker.ticks) ticks"
}
.bindTo(footer.rx.text)

This API uses the Realm object notifications under the hood to listen for changes.

This method will by default emit the object initial state as its first next event. You can disable this behavior by using the emitInitialValue parameter and setting it to false.

Finally you can set changes to which properties constitute an object change you'd like to observe for:

rvable.from(object: ticker, properties: ["name", "id", "family"]) ...
Write transactions
rx.add()

Writing objects to existing realm reference. You can add newly created objects to a Realm that you already have initialized:

realm = try! Realm()
messages = [Message("hello"), Message("world")]

rvable.from(messages)
ubscribe(realm.rx.add())

Be careful, this will retain your Realm until the Observable completes or errors out.

Realm.rx.add()

Writing to the default Realm. You can leave it to RxRealm to grab the default Realm on any thread your subscribe and write objects to it:

messages = [Message("hello"), Message("world")]

rvable.from(messages)
ubscribe(Realm.rx.add())
Realm.rx.add(configuration:)

Writing to a custom Realm. If you want to switch threads and not use the default Realm, provide a Realm.Configuration. You an also provide an error handler for the observer to be called if either creating the realm reference or the write transaction raise an error:

config = Realm.Configuration()
ustom configuration settings */

messages = [Message("hello"), Message("world")]
rvable.from(messages)
bserveOn( /* you can switch threads here */ )     
ubscribe(Realm.rx.add(configuration: config, onError: {elements, error in
if let elements = elements {
  print("Error \(error.localizedDescription) while saving objects \(String(describing: elements))")
} else {
  print("Error \(error.localizedDescription) while opening realm.")
}
)

If you want to create a Realm on a different thread manually, allowing you to handle errors, you can do that too:

messages = [Message("hello"), Message("world")]

rvable.from(messages)
bserveOn( /* you can switch threads here */ )
ubscribe(onNext: {messages in
let realm = try! Realm()
try! realm.write {
  realm.add(messages)
}

rx.delete()

Deleting object(s) from an existing realm reference:

realm = try! Realm()
messages = realm.objects(Message.self)
rvable.from(messages)
ubscribe(realm.rx.delete())

Be careful, this will retain your realm until the Observable completes or errors out.

Realm.rx.delete()

Deleting from the object's realm automatically. You can leave it to RxRealm to grab the Realm from the first object and use it:

rvable.from(someCollectionOfPersistedObjects)
ubscribe(Realm.rx.delete())
Automatically binding table and collection views

RxRealm does not depend on UIKit/Cocoa and it doesn't provide built-in way to bind Realm collections to UI components.

a) Non-animated binding

You can use the built-in RxCocoa bindTo(_:) method, which will automatically drive your table view from your Realm results:

rvable.from( [Realm collection] )
indTo(tableView.rx.items) {tv, ip, element in
let cell = tv.dequeueReusableCell(withIdentifier: "Cell")!
cell.textLabel?.text = element.text
return cell

ddDisposableTo(bag)
b) Animated binding with RxRealmDataSources

The separate library RxRealmDataSources mimics the default data sources library behavior for RxSwift.

RxRealmDataSources allows you to bind an observable collection of Realm objects directly to a table or collection view:

reate data source
dataSource = RxTableViewRealmDataSource<Lap>(
llIdentifier: "Cell", cellType: PersonCell.self) {cell, ip, lap in
cell.customLabel.text = "\(ip.row). \(lap.text)"


xRealm to get Observable<Results>
realm = try! Realm()
lapsList = realm.objects(Timer.self).first!.laps
laps = Observable.changeset(from: lapsList)

ind to table view

indTo(tableView.rx.realmChanges(dataSource))
ddDisposableTo(bag)

The data source will reflect all changes via animations to the table view:

RxRealm animated changes

If you want to learn more about the features beyond animating changes, check the RxRealmDataSources README.

Example app

To run the example project, clone the repo, and run pod install from the Example directory first. The app uses RxSwift, RxCocoa using RealmSwift, RxRealm to observe Results from Realm.

Further you're welcome to peak into the RxRealmTests folder of the example app, which features the library's unit tests.

Installation

This library depends on both RxSwift and RealmSwift 1.0+.

CocoaPods

RxRealm requires CocoaPods 1.1.x or higher.

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

"RxRealm"
Carthage

To integrate RxRealm into your Xcode project using Carthage, specify it in your Cartfile:

ub "RxSwiftCommunity/RxRealm"

Run carthage update to build the framework and drag the built RxRealm.framework into your Xcode project.

TODO
License

This library belongs to RxSwiftCommunity. Maintainer is Marin Todorov.

RxRealm 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.