From 8026e83ba45f34754c4a982ed668d8797d7957bd Mon Sep 17 00:00:00 2001 From: Marin Todorov Date: Sat, 23 Apr 2016 23:16:36 +0200 Subject: [PATCH 1/3] didn't need this file --- _Pods.xcodeproj | 1 - 1 file changed, 1 deletion(-) delete mode 120000 _Pods.xcodeproj diff --git a/_Pods.xcodeproj b/_Pods.xcodeproj deleted file mode 120000 index 3c5a8e7..0000000 --- a/_Pods.xcodeproj +++ /dev/null @@ -1 +0,0 @@ -Example/Pods/Pods.xcodeproj \ No newline at end of file From cdac0fa9356b7e7e01ae48ac0eeb4b03417fdfa0 Mon Sep 17 00:00:00 2001 From: Marin Todorov Date: Sun, 24 Apr 2016 11:17:42 +0200 Subject: [PATCH 2/3] * 0.1.3 first draft --- Example/RxRealm_Tests/RxRealmTests.swift | 170 ++++++++++++++++++++--- Pod/Classes/RxRealm.swift | 31 +++++ README.md | 40 ++++-- 3 files changed, 208 insertions(+), 33 deletions(-) diff --git a/Example/RxRealm_Tests/RxRealmTests.swift b/Example/RxRealm_Tests/RxRealmTests.swift index e20f057..54212e0 100644 --- a/Example/RxRealm_Tests/RxRealmTests.swift +++ b/Example/RxRealm_Tests/RxRealmTests.swift @@ -11,6 +11,11 @@ import RealmSwift import RxRealm import RxTests +func delay(delay: Double, closure: () -> Void) { + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))), + dispatch_get_main_queue(), closure) +} + class Message: Object, Equatable { dynamic var text = "" convenience init(_ text: String) { @@ -25,25 +30,19 @@ func ==(lhs: Message, rhs: Message) -> Bool { class RxRealm_Tests: XCTestCase { - var bag: DisposeBag! = DisposeBag() - - override func setUp() { - super.setUp() - Realm.Configuration.defaultConfiguration.inMemoryIdentifier = "MemoryRealm" + private func realmInMemory(name: String) -> Realm { + var conf = Realm.Configuration() + conf.inMemoryIdentifier = name + return try! Realm(configuration: conf) } - override func tearDown() { - bag = nil - super.tearDown() - } - private func clearRealm(realm: Realm) { try! realm.write { realm.deleteAll() } } - private func addObject(realm: Realm, text: String) { + private func addMessage(realm: Realm, text: String) { try! realm.write { realm.add(Message(text)) } @@ -53,8 +52,9 @@ class RxRealm_Tests: XCTestCase { let expectation1 = expectationWithDescription("Results first") let expectation2 = expectationWithDescription("Results second") - let realm = try! Realm() + let realm = realmInMemory(#function) clearRealm(realm) + let bag = DisposeBag() let scheduler = TestScheduler(initialClock: 0) let observer = scheduler.createObserver(Results) @@ -70,9 +70,11 @@ class RxRealm_Tests: XCTestCase { messages$.subscribe(observer).addDisposableTo(bag) - addObject(realm, text: "first") + addMessage(realm, text: "first(Results)") - performSelector(#selector(addSecondMessage), withObject: nil, afterDelay: 0.1) + delay(0.1) { + self.addMessage(realm, text: "second(Results)") + } scheduler.start() @@ -80,8 +82,8 @@ class RxRealm_Tests: XCTestCase { XCTAssertTrue(error == nil) XCTAssertEqual(observer.events.count, 2) let results = observer.events.last!.value.element! - XCTAssertTrue(results.first! == Message("first")) - XCTAssertTrue(results.last! == Message("second")) + XCTAssertTrue(results.first! == Message("first(Results)")) + XCTAssertTrue(results.last! == Message("second(Results)")) } } @@ -89,8 +91,9 @@ class RxRealm_Tests: XCTestCase { let expectation1 = expectationWithDescription("Array first") let expectation2 = expectationWithDescription("Array second") - let realm = try! Realm() + let realm = realmInMemory(#function) clearRealm(realm) + let bag = DisposeBag() let scheduler = TestScheduler(initialClock: 0) let observer = scheduler.createObserver(Array) @@ -106,21 +109,142 @@ class RxRealm_Tests: XCTestCase { messages$.subscribe(observer).addDisposableTo(bag) - addObject(realm, text: "first") + addMessage(realm, text: "first(Array)") - performSelector(#selector(addSecondMessage), withObject: nil, afterDelay: 0.1) + delay(0.1) { + self.addMessage(realm, text: "second(Array)") + } scheduler.start() waitForExpectationsWithTimeout(0.5) {error in XCTAssertTrue(error == nil) XCTAssertEqual(observer.events.count, 2) - XCTAssertTrue(observer.events.first!.value.element! == [Message("first")]) - XCTAssertTrue(observer.events.last!.value.element! == [Message("first"), Message("second")]) + XCTAssertTrue(observer.events.first!.value.element! == [Message("first(Array)")]) + XCTAssertTrue(observer.events.last!.value.element! == [Message("first(Array)"), Message("second(Array)")]) } } - func addSecondMessage() { - addObject(try! Realm(), text: "second") + func testEmittedChangeset() { + let expectation1 = expectationWithDescription("did emit all changeset values") + + let realm = realmInMemory(#function) + clearRealm(realm) + let bag = DisposeBag() + + let scheduler = TestScheduler(initialClock: 0) + let observer = scheduler.createObserver(String) + + //initial data + addMessage(realm, text: "first(Changeset)") + + let messages$ = realm.objects(Message).asObservableChangeset().shareReplay(1) + messages$.scan(0) { count, _ in + return count+1 + } + .filter {$0 == 3} + .subscribeNext {_ in expectation1.fulfill() } + .addDisposableTo(bag) + + messages$ + .map {result, changes in + if let changes = changes { + return "count:\(result.count) inserted:\(changes.inserted) deleted:\(changes.deleted) updated:\(changes.updated)" + } else { + return "count:\(result.count)" + } + } + .subscribe(observer).addDisposableTo(bag) + + //insert + delay(0.25) { + self.addMessage(realm, text: "second(Changeset)") + } + //update + delay(0.5) { + try! realm.write { + realm.delete(realm.objects(Message).filter("text='first(Changeset)'").first!) + realm.objects(Message).filter("text='second(Changeset)'").first!.text = "third(Changeset)" + } + } + //coalesced + delay(0.7) { + self.addMessage(realm, text: "first(Changeset)") + } + delay(0.7) { + try! realm.write { + realm.delete(realm.objects(Message).filter("text='first(Changeset)'").first!) + } + } + + waitForExpectationsWithTimeout(0.75) {error in + XCTAssertTrue(error == nil) + XCTAssertEqual(observer.events.count, 3) + XCTAssertEqual(observer.events[0].value.element!, "count:1") + XCTAssertEqual(observer.events[1].value.element!, "count:2 inserted:[1] deleted:[] updated:[]") + XCTAssertEqual(observer.events[2].value.element!, "count:1 inserted:[] deleted:[0] updated:[1]") + } + } + + func testEmittedArrayChangeset() { + let expectation1 = expectationWithDescription("did emit all array changeset values") + + let realm = realmInMemory(#function) + clearRealm(realm) + let bag = DisposeBag() + + let scheduler = TestScheduler(initialClock: 0) + let observer = scheduler.createObserver(String) + + //initial data + addMessage(realm, text: "first(ArrayChangeset)") + + let messages$ = realm.objects(Message).asObservableArrayChangeset().shareReplay(1) + messages$.scan(0) { count, _ in + return count+1 + } + .filter {$0 == 3} + .subscribeNext {_ in expectation1.fulfill() } + .addDisposableTo(bag) + + messages$ + .map {result, changes in + if let changes = changes { + return "count:\(result.count) inserted:\(changes.inserted) deleted:\(changes.deleted) updated:\(changes.updated)" + } else { + return "count:\(result.count)" + } + } + .subscribe(observer).addDisposableTo(bag) + + //insert + delay(0.25) { + self.addMessage(realm, text: "second(ArrayChangeset)") + } + //update + delay(0.5) { + try! realm.write { + realm.delete(realm.objects(Message).filter("text='first(ArrayChangeset)'").first!) + realm.objects(Message).filter("text='second(ArrayChangeset)'").first!.text = "third(ArrayChangeset)" + } + } + //coalesced + delay(0.7) { + self.addMessage(realm, text: "first(ArrayChangeset)") + } + delay(0.7) { + try! realm.write { + realm.delete(realm.objects(Message).filter("text='first(ArrayChangeset)'").first!) + } + } + + waitForExpectationsWithTimeout(0.75) {error in + XCTAssertTrue(error == nil) + XCTAssertEqual(observer.events.count, 3) + XCTAssertEqual(observer.events[0].value.element!, "count:1") + XCTAssertEqual(observer.events[1].value.element!, "count:2 inserted:[1] deleted:[] updated:[]") + XCTAssertEqual(observer.events[2].value.element!, "count:1 inserted:[] deleted:[0] updated:[1]") + } } + } \ No newline at end of file diff --git a/Pod/Classes/RxRealm.swift b/Pod/Classes/RxRealm.swift index 7d656eb..50f5075 100644 --- a/Pod/Classes/RxRealm.swift +++ b/Pod/Classes/RxRealm.swift @@ -16,6 +16,12 @@ extension List: NotificationEmitter {} extension AnyRealmCollection: NotificationEmitter {} extension Results: NotificationEmitter {} +public struct RealmChangeset { + public let deleted: [Int] + public let inserted: [Int] + public let updated: [Int] +} + public extension NotificationEmitter where Self: RealmCollectionType { public func asObservable() -> Observable { @@ -48,4 +54,29 @@ public extension NotificationEmitter where Self: RealmCollectionType { public func asObservableArray() -> Observable> { return asObservable().map { Array($0) } } + + public func asObservableChangeset() -> Observable<(Self, RealmChangeset?)> { + return Observable.create {observer in + let token = self.addNotificationBlock {changeset in + + switch changeset { + case .Initial(let value): + observer.onNext((value, nil)) + case .Update(let value, let deletes, let inserts, let updates): + observer.onNext((value, RealmChangeset(deleted: deletes, inserted: inserts, updated: updates))) + case .Error(let error): + observer.onError(error) + return + } + } + + return AnonymousDisposable { + token.stop() + } + } + } + + public func asObservableArrayChangeset() -> Observable<(Array, RealmChangeset?)> { + return asObservableChangeset().map { (Array($0), $1) } + } } \ No newline at end of file diff --git a/README.md b/README.md index 99e1a17..4d94245 100644 --- a/README.md +++ b/README.md @@ -8,9 +8,9 @@ This library is a very thin wrapper around the reactive collection types __RealmSwift__ provides: `Results`, `List` and `AnyRealmCollection`. -The extension adds two methods to all of the above: +The extension adds these methods to all of the above: -### asObservable() +#### asObservable() `asObservable()` - emits every time the collection changes: ```swift @@ -22,7 +22,7 @@ realm.objects(Lap).asObservable() } ``` -### asObservableArray() +#### asObservableArray() `asObservableArray()` - fetches the a snapshot of a Realm collection and converts it to an array value (for example if you want to use array methods on the collection): ```swift @@ -36,29 +36,48 @@ realm.objects(Lap).asObservableArray() } ``` +#### asObservableChangeset() +`asObservableChangeset()` - emits every time the collection changes and provides the exact indexes that has been deleted, inserted or updated: -## Example app +```swift +let realm = try! Realm() +realm.objects(Lap).asObservableChangeset() + .subscribeNext {result, changes in + if let changes = changes { + //it's an update + print(result) + print("deleted: \(changes.deleted) inserted: \(changes.inserted) updated: \(changes.updated)") + } else { + //it's the initial data + print(result) + } + } +``` -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. +#### asObservableArrayChangeset() + +`asObservableArrayChangeset()` combines the result of `asObservableArray()` and `asObservableChangeset()` returning an `Observable, RealmChangeset?>`. -## Requirements +#### Example app -This library depends on both __RxSwift__ and __RealmSwift__. +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. ## Installation -### CocoaPods +This library depends on both __RxSwift__ and __RealmSwift__ 0.99+. + +#### CocoaPods RxRealm is available through [CocoaPods](http://cocoapods.org). To install it, simply add the following line to your Podfile: ```ruby pod "RxRealm" ``` -### Carthage +#### Carthage Feel free to send a PR -### As Source +#### As Source You can grab the __RxRealm.swift__ file from this repo and include it in your project. @@ -71,6 +90,7 @@ This library belongs to _RxSwiftCommunity_ and is based on the work of [@fpillet * Carthage * Add `asObservable()` to the Realm class * Test add platforms and add compatibility for the pod +* Document the source code ## License From 52a2e005d86a82736217e50e0c2701b053fb34f8 Mon Sep 17 00:00:00 2001 From: Marin Todorov Date: Sun, 24 Apr 2016 11:18:19 +0200 Subject: [PATCH 3/3] * bumped up pod spec --- RxRealm.podspec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/RxRealm.podspec b/RxRealm.podspec index 4f9ad47..0644c65 100644 --- a/RxRealm.podspec +++ b/RxRealm.podspec @@ -1,7 +1,7 @@ Pod::Spec.new do |s| s.name = "RxRealm" - s.version = "0.1.2" + s.version = "0.1.3" s.summary = "An Rx wrapper of Realm's collection type" s.description = <<-DESC