Szu
Szu

Reputation: 2252

Realm notification to RX block

I would like to hide my Realm implementation and instead of working on RLMNotificationBlock I would like to use RXSwift. Below how my method looks like now (RLMNotificationBlock is a block that takes String and RLMRealm):

func addNotificationBlock(block: RLMNotificationBlock) -> RLMNotificationToken? {
    let rlmObject = ...
    return rlmObject.addNotificationBlock(block)
}

But I would like to switch to more reactive observer-pattern way. I looked at RxSwift docs and source code of rx_clickedButtonAtIndex, but I cannot figure out how I should put all these things together. I guess my code at the end would look like:

public var rx_realmContentChanged: ControlEvent<Int> {
    let controlEvent = ControlEvent()
    // My code go here
    return controlEvent
}

I'm new with RXSwift and know only the basics. Any help will be appreciated.

Upvotes: 1

Views: 1082

Answers (2)

Marin Todorov
Marin Todorov

Reputation: 6397

There is an Rx Realm extension available on GitHub you can use: https://github.com/RxSwiftCommunity/RxRealm

It allows you to get an Observable out of a single Realm object or a Realm Collection. Here's an example from the README:

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

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

There is also an additional library especially built for binding table and collection views called RxRealmDataSources

Upvotes: 1

Serg Dort
Serg Dort

Reputation: 487

If I understood you correctly, you just want to return Observable<RLMNotificationToken> In this case you just need to do something like this

func addNotificationBlock(block: RLMNotificationBlock) -> Observable<RLMNotificationToken> {
    return create { observer -> Disposable in
        let rlmObject = ...
        let token = rlmObject.addNotificationBlock(block)

        // Some condition
        observer.onNext(token)
        // Some other condition
        observer.onError(NSError(domain: "My domain", code: -1, userInfo: nil))

        return AnonymousDisposable {
            // Dispose resources here
        }
        // If you have nothing to dipose return `NopDisposable.instance`
    }
}

In order to use it bind it to button rx_tap or other use flatMap operator

Upvotes: 1

Related Questions