29
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Realm の通知を RxSwift の Observable に包み込む

Last updated at Posted at 2016-03-28

Realm のクエリ結果が変化するたびに RxSwift のストリームに結果が流れる処理を考えてみました。
Realm の通知トークンが購読中は強参照になるのが肝です。

realm.objects(Dog).filter("age > 3").rx_response()
    .subscribeNext { /* UI の更新処理 */ }
    .addDisposableTo(disposeBag)

実装

RxCocoa/UIControl+Rx.swift を参考

import RxSwift
import RealmSwift

extension Results {
    
    public func rx_response() -> Observable<Results<Element>> {
        return Observable.create { observer in
            
            MainScheduler.ensureExecutingOnScheduler()
            
            let token = self.addNotificationBlock { results, error in
                
                if let error = error {
                    observer.onError(error)
                } else {
                    observer.onNext(results!)
                }
            }
            
            return AnonymousDisposable {
                token.stop()
            }
        }
    }
}

29
27
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
29
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?