Skip to content

Instantly share code, notes, and snippets.

@fpillet
Created February 13, 2016 17:23
Show Gist options
  • Save fpillet/4ceb477eeb2705fb5159 to your computer and use it in GitHub Desktop.
Save fpillet/4ceb477eeb2705fb5159 to your computer and use it in GitHub Desktop.
turn Realm auto-updating Results into an RxSwift Observable sequence
//
// Results+Rx.swift
//
// Make Realm auto-updating Results observable. Works with Realm 0.98 and later, RxSwift 2.1.0 and later.
//
// Created by Florent Pillet on 12/02/16.
// Copyright (c) 2016 Florent Pillet. All rights reserved.
//
import Foundation
import RealmSwift
import RxSwift
extension Results {
/// turn a Realm Results into an Observable sequence that sends the Results object itself once at query, then
/// again every time a change occurs in the Results. Caller just subscribes to the observable to get
/// updates. Note that Realm may send updates even when there is no actual change to the data
/// (Realm docs mention they will fine tune this later)
func asObservable() -> Observable<Results<Element>> {
return Observable.create { observer in
var token: NotificationToken? = nil
token = self.addNotificationBlock { (results, error) in
guard error == nil else {
observer.onError(error!)
return
}
observer.onNext(results!)
}
return AnonymousDisposable {
token?.stop()
}
}
}
/// turn a Realm Results into an Observable sequence that sends the Results object itself once at query, then
/// again every time a change occurs in the Results. Caller just subscribes to the observable to get
/// updates. Note that Realm may send updates even when there is no actual change to the data
/// (Realm docs mention they will fine tune this later)
func asObservableArray() -> Observable<[Element]> {
return Observable.create { observer in
var token: NotificationToken? = nil
token = self.addNotificationBlock { (results, error) in
guard error == nil else {
observer.onError(error!)
return
}
observer.onNext(Array(self))
}
return AnonymousDisposable {
token?.stop()
}
}
}
}
@phamquochoan
Copy link

do we need to add [unowned self] or [weak self] into these functions ?

@fpillet
Copy link
Author

fpillet commented Apr 17, 2016

@phamquochoan: I don't think so. In the second API you're right that we're using self in the closure so essentially keeping it alive -- but this is what we want! As long as we keep observing the Results, they will stay alive. It's when we dispose our subscription that we don't need Results anymore.

@timbodeit
Copy link

Would be awesome to have this as a Cocoapod.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment