Convert Figma logo to code with AI

RxSwiftCommunity logoRxRealm

RxSwift extension for RealmSwift's types

1,153
264
1,153
14

Top Related Projects

24,320

Reactive Programming in Swift

Realm is a mobile database: a replacement for Core Data & SQLite

Cocoa framework and Obj-C dynamism bindings for ReactiveSwift.

15,085

Network abstraction layer written in Swift.

A Swift Reactive Programming Kit

4,233

A Swift binding framework

Quick Overview

RxRealm is a library that provides RxSwift extensions for Realm, a mobile database solution. It allows developers to observe Realm objects and collections using RxSwift, enabling reactive programming patterns when working with Realm databases in iOS and macOS applications.

Pros

  • Seamless integration of RxSwift with Realm, combining the power of reactive programming and efficient local data storage
  • Simplifies data binding and synchronization between Realm objects and UI components
  • Provides a wide range of operators for transforming and manipulating Realm data streams
  • Supports both object and collection observations, offering flexibility in data handling

Cons

  • Requires knowledge of both RxSwift and Realm, which may increase the learning curve for developers new to either technology
  • Adds an additional dependency to projects, potentially increasing app size and complexity
  • May introduce performance overhead in some scenarios due to the reactive nature of operations
  • Limited documentation and examples compared to more mainstream libraries

Code Examples

  1. Observing changes in a Realm object:
let realm = try! Realm()
let person = realm.objects(Person.self).first!

Observable.from(object: person)
    .subscribe(onNext: { change in
        print("Person changed: \(change.property)")
    })
    .disposed(by: disposeBag)
  1. Observing a Realm collection:
let realm = try! Realm()
let dogs = realm.objects(Dog.self)

Observable.collection(from: dogs)
    .subscribe(onNext: { changes in
        print("Dogs collection changed: \(changes)")
    })
    .disposed(by: disposeBag)
  1. Binding Realm results to a table view:
let realm = try! Realm()
let persons = realm.objects(Person.self)

Observable.collection(from: persons)
    .bind(to: tableView.rx.items(cellIdentifier: "PersonCell", cellType: PersonCell.self)) { row, person, cell in
        cell.configure(with: person)
    }
    .disposed(by: disposeBag)

Getting Started

  1. Install RxRealm using CocoaPods by adding the following to your Podfile:
pod 'RxRealm'
  1. Import RxRealm in your Swift file:
import RxRealm
  1. Start using RxRealm with Realm objects and collections:
let realm = try! Realm()
let dogs = realm.objects(Dog.self)

Observable.collection(from: dogs)
    .subscribe(onNext: { changes in
        print("Dogs collection changed")
    })
    .disposed(by: disposeBag)

Competitor Comparisons

24,320

Reactive Programming in Swift

Pros of RxSwift

  • Comprehensive reactive programming framework for Swift
  • Large community and extensive documentation
  • Supports a wide range of reactive operators and patterns

Cons of RxSwift

  • Steeper learning curve for developers new to reactive programming
  • Can lead to complex code if not used judiciously
  • Larger codebase and potential performance overhead

Code Comparison

RxSwift:

Observable.from([1, 2, 3, 4, 5])
    .filter { $0 % 2 == 0 }
    .map { $0 * 2 }
    .subscribe(onNext: { print($0) })

RxRealm:

let realm = try! Realm()
let results = realm.objects(MyObject.self)
Observable.collection(from: results)
    .subscribe(onNext: { changes in
        // Handle changes
    })

Key Differences

  • RxSwift is a general-purpose reactive framework, while RxRealm is specifically designed for Realm database integration
  • RxRealm provides a simpler API for working with Realm objects reactively
  • RxSwift offers more flexibility and a broader range of operators for complex reactive scenarios

Use Cases

  • Choose RxSwift for general reactive programming needs in Swift projects
  • Opt for RxRealm when working specifically with Realm databases and requiring reactive data observation

Realm is a mobile database: a replacement for Core Data & SQLite

Pros of realm-swift

  • Native Swift implementation, offering better performance and deeper integration with Swift language features
  • More comprehensive documentation and extensive community support
  • Broader feature set, including encryption, notifications, and multi-threading support

Cons of realm-swift

  • Steeper learning curve due to its unique approach to data modeling
  • Less flexibility in terms of database schema changes, which can be challenging in evolving projects

Code Comparison

RxRealm:

Observable.collection(from: realm.objects(Person.self))
    .subscribe(onNext: { results in
        print("Persons: \(results)")
    })

realm-swift:

let persons = realm.objects(Person.self)
let token = persons.observe { changes in
    switch changes {
    case .initial(let results):
        print("Initial persons: \(results)")
    case .update(let results, _, _, _):
        print("Updated persons: \(results)")
    case .error(let error):
        print("Error: \(error)")
    }
}

RxRealm provides a more concise, reactive approach to observing database changes, while realm-swift offers more granular control over change types and error handling. The choice between the two depends on whether you prefer a reactive programming style or a more traditional approach to database interactions.

Cocoa framework and Obj-C dynamism bindings for ReactiveSwift.

Pros of ReactiveCocoa

  • More comprehensive framework with a wider range of reactive programming features
  • Supports both Objective-C and Swift, providing better compatibility for legacy projects
  • Offers a rich set of operators and transformations for complex data flows

Cons of ReactiveCocoa

  • Steeper learning curve due to its extensive API and concepts
  • Heavier framework with potentially larger app size and longer compilation times
  • Less focused on Realm database integration compared to RxRealm

Code Comparison

ReactiveCocoa:

let (signal, observer) = Signal<String, Never>.pipe()
signal.observeValues { value in
    print("Received value: \(value)")
}
observer.send(value: "Hello, ReactiveCocoa!")

RxRealm:

let realm = try! Realm()
let results = realm.objects(Person.self)
Observable.collection(from: results)
    .subscribe(onNext: { changes in
        print("Received changes: \(changes)")
    })

The ReactiveCocoa example demonstrates creating a signal and observing its values, while the RxRealm example shows observing changes in a Realm collection. RxRealm provides a more streamlined API for working with Realm databases in a reactive manner, while ReactiveCocoa offers a more general-purpose reactive programming approach.

15,085

Network abstraction layer written in Swift.

Pros of Moya

  • Provides a network abstraction layer, simplifying API interactions
  • Supports easy testing and stubbing of network requests
  • Offers type-safe API definitions using enums

Cons of Moya

  • Steeper learning curve for developers new to the concept
  • May be overkill for simple API integrations
  • Requires additional setup and configuration

Code Comparison

Moya:

enum GitHub {
    case zen
    case userProfile(String)
}

extension GitHub: TargetType {
    var baseURL: URL { return URL(string: "https://api.github.com")! }
    var path: String {
        switch self {
        case .zen:
            return "/zen"
        case .userProfile(let name):
            return "/users/\(name)"
        }
    }
}

RxRealm:

let realm = try! Realm()
let results = realm.objects(Dog.self).filter("name contains 'Fido'")

Observable.collection(from: results)
    .subscribe(onNext: { results in
        print("Results: \(results)")
    })

Note: RxRealm focuses on integrating Realm with RxSwift, while Moya is a network abstraction layer. They serve different purposes and are not direct competitors.

A Swift Reactive Programming Kit

Pros of ReactiveKit

  • More comprehensive reactive programming framework, not limited to Realm
  • Supports a wider range of reactive programming patterns and use cases
  • Active development with frequent updates and improvements

Cons of ReactiveKit

  • Steeper learning curve due to its broader scope
  • May be overkill for projects only requiring Realm integration
  • Less specialized for Realm-specific operations

Code Comparison

ReactiveKit:

let signal = Signal<Int, Never>(just: 1)
signal.observe { value in
    print(value)
}

RxRealm:

let realm = try! Realm()
let results = realm.objects(MyObject.self)
Observable.collection(from: results)
    .subscribe(onNext: { changes in
        print(changes)
    })

ReactiveKit provides a more general-purpose reactive programming approach, while RxRealm focuses specifically on integrating Realm with RxSwift. ReactiveKit offers greater flexibility for various reactive scenarios, but RxRealm provides a more streamlined experience for Realm-based reactive programming in Swift projects.

4,233

A Swift binding framework

Pros of Bond

  • More comprehensive framework for reactive programming, offering a wider range of features beyond just Realm integration
  • Supports multiple data sources and bindings, not limited to Realm databases
  • Provides a declarative approach to UI development, which can lead to cleaner and more maintainable code

Cons of Bond

  • Steeper learning curve due to its broader scope and more complex API
  • May introduce unnecessary overhead for projects that only require Realm integration
  • Less focused on Realm-specific optimizations compared to RxRealm

Code Comparison

Bond example:

let observable = Observable<String>("")
observable.bind(to: textField.reactive.text)

RxRealm example:

let realm = try! Realm()
let results = realm.objects(Person.self)
Observable.collection(from: results)
    .subscribe(onNext: { changes in
        // Handle changes
    })

Both libraries provide reactive extensions for working with data, but Bond offers a more general-purpose approach, while RxRealm is specifically tailored for Realm database operations. The choice between the two depends on the project's requirements and the developer's preference for a focused or comprehensive reactive programming solution.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

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.