Swiftpack.co - Package - RxSwiftCommunity/RxRealm
Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.

RxRealm

Carthage Compatible Version Swift Package Manager compatible 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:

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

Observable.collection(from: laps)
  .map { 
    laps in "\(laps.count) laps"
  }
  .subscribe(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):

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

Observable.array(from: laps)
  .map { array in
    return array.prefix(3) //slice of first 3 items
  }
  .subscribe(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:

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

Observable.changeset(from: laps)
  .subscribe(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?>

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

Observable.arrayWithChangeset(from: laps)
  .subscribe(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:

Observable.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:

Observable.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:

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

Observable.from(messages)
  .subscribe(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:

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

Observable.from(messages)
  .subscribe(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:

var config = Realm.Configuration()
/* custom configuration settings */

let messages = [Message("hello"), Message("world")]
Observable.from(messages)
  .observeOn( /* you can switch threads here */ )     
  .subscribe(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:

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

Observable.from(messages)
  .observeOn( /* you can switch threads here */ )
  .subscribe(onNext: {messages in
    let realm = try! Realm()
    try! realm.write {
      realm.add(messages)
    }
  })
rx.delete()

Deleting object(s) from an existing realm reference:

let realm = try! Realm()
let messages = realm.objects(Message.self)
Observable.from(messages)
  .subscribe(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:

Observable.from(someCollectionOfPersistedObjects)
  .subscribe(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:

Observable.from( [Realm collection] )
  .bindTo(tableView.rx.items) {tv, ip, element in
    let cell = tv.dequeueReusableCell(withIdentifier: "Cell")!
    cell.textLabel?.text = element.text
    return cell
  }
  .addDisposableTo(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:

// create data source
let dataSource = RxTableViewRealmDataSource<Lap>(
  cellIdentifier: "Cell", cellType: PersonCell.self) {cell, ip, lap in
    cell.customLabel.text = "\(ip.row). \(lap.text)"
}

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

// bind to table view
laps
  .bindTo(tableView.rx.realmChanges(dataSource))
  .addDisposableTo(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:

pod "RxRealm"

Carthage

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

github "RxSwiftCommunity/RxRealm"

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

Swift Package Manager

In your Package.swift:

let package = Package(
  name: "Example",
  dependencies: [
    .package(url: "https://github.com/RxSwiftCommunity/RxRealm.git", from: "1.0.1")
  ],
  targets: [
    .target(name: "Example", dependencies: ["RxRealm"])
  ]
)

TODO

  • Test add platforms and add compatibility for the pod

License

This library belongs to RxSwiftCommunity. Maintainer is Marin Todorov.

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

Github

link
Stars: 994

Releases

RxRealm v5.0.1 - 2021-01-05T08:13:05

RxRealm v5.0.0 - 2021-01-03T09:26:43

RxRealm v4.0.3 - 2020-12-20T03:26:19

RxRealm v4.0.2 - 2020-12-05T15:33:59

RxRealm v4.0.1 - 2020-12-05T14:40:15

4.0.0: Realm 10 - 2020-12-01T10:28:27

Support Realm 10

This project is looking for a new owner/maintainer. Please ping me on Twitter or Slack if you're interested (@freak4pc).

3.1.0: Support Realm 5.2.0 - 2020-07-06T13:15:27

Bump minimum iOS version to 9.0 to sync with realm-cocoa https://github.com/realm/realm-cocoa/releases/tag/v5.2.0

3.0.0: Support Realm 5 - 2020-06-04T10:47:39

2.0.0: Support Realm 4.0.0 - 2019-11-22T04:07:55

1.0.1: Support SPM - 2019-08-16T10:23:34

RxRealm 1.0.0 (Swift 5) - 2019-05-08T11:27:15

Support for Swift 5 & Xcode 10.2. Thanks @rynecheow !

Carthage Swift 4.2 - 2018-12-11T18:45:18

Swift 4.2 update - 2018-09-23T10:20:58

Swift 4.2 update

RxBlocking Migration - 2017-11-30T16:23:23

This release migrates the test suite to RxBlocking - much readable, very stable 🐕

Hello back iOS8! - 2017-10-27T13:20:40

Relaxing min ios version

Swift4/RxSwift4/RealmSwift3 - 2017-10-20T08:47:16

This release brings compatibility with swift4, rxswift4, and realmswift3. Enjoy

Xcode9Carthage - 2017-10-05T13:26:25

  • Updates compatibility with Xcode9 via Carthage
  • Updates some outdated syntax in the demo/tests

RxSwift-RealmSwift-beta - 2017-09-26T14:00:08

Dependencies of: 'RealmSwift', '3.0.0-beta.4'; 'RxSwift', '4.0.0-beta.0'

Hello, RxSwift4 - alpha.1 - 2017-08-22T13:25:47

NB: This is a pre-release alpha quality code!

This pre- release uses the 4.0-alpha.1 branch of RxSwift and the 2.9.* versions of RealmSwift. The demo app successfully builds and runs on Xcode9 and Swift 4.

If you'd like to use this code to test your own RxSwift/Realm apps in Xode9/Swift4 you will need to use the alpha versions of RxSwift and RxRealm. For an example of the Podfile you need to do that check out the demo app in the RxRealm repo here:

https://github.com/RxSwiftCommunity/RxRealm/blob/mt/swift4.0/Example/Podfile

Hello, write error handling - 2017-04-13T12:27:52

This release adds:

  • error handling closure to write observer

Fixes:

  • out of sync crash with latest RxSwift
  • lots of source re-formatting to make it look good
  • renamed few generic types S for sequences, O for objects

Hello Object Notifications - 2017-03-07T14:39:10

An update requiring RealmSwift 2.4 that integrates native object notifications. Also adds tvOS and watchOS as supported targets.

Includes PRs: https://github.com/RxSwiftCommunity/RxRealm/pull/68 https://github.com/RxSwiftCommunity/RxRealm/pull/71

0.5.0 Update - 2017-01-23T12:28:56

Few small changes to 0.5.0 before releasing to CocoaPods

RxSwift31Compatibility - 2017-01-19T12:27:50

RxSwift 3.1 breaks all custom overrides of Observable.from() so RxRealm had to move to a new naming for its methods. This is a rather big update with the following features:

  • renamed all methods to avoid RxSwift 3.1 clash …
  • added deprecated availability to all deprecated methods
  • did a pass on coding style
  • added updated docs to all changed methods
  • removed scheduler parameters, which weren't used
  • added synchronousStart parameter to toggle sync/async first emit
  • added new tests for sync/async emits

DependenceDay - 2016-12-30T12:02:42

This update bumps the dependencies version up and fixes compatibility issues

RxRealmDataSources compatibility - 2016-12-11T21:26:56

! Breaking changes! This version type erases the emitted collection from changesetFrom(...) method in order to allow for different observers to observe the sequence.

Single Object Crash Fix - 2016-11-25T08:50:20

the standard swift lib function type(of:) crashes on the device so this version uses a workaround that doesn't need this function. Enjoy!

Single Object Observing - 2016-11-01T12:04:33

This release adds the possibility to observe a Realm object you already have your hands on, like so: Observable.from(myObject).subscribe(onNext: {value in ....}) etc.

RxSwift 3.0.0 support - 2016-10-25T09:01:41

This release will get you running with the stable RxSwift 3.0.0 release 🌟

watch! - 2016-10-09T14:36:58

adds watchOS, still running on RxSwift 3.0.0 beta.2

rxswift3 b2 + realm 2 - 2016-10-09T07:39:20

This release uses the latest beta 2 of RxSwift + RealmSwift 2.0+