Skip to content

Instantly share code, notes, and snippets.

@ukitaka
Created May 30, 2016 02:14
Show Gist options
  • Save ukitaka/bed11d8c874f4b4f5c467a322ad5eed5 to your computer and use it in GitHub Desktop.
Save ukitaka/bed11d8c874f4b4f5c467a322ad5eed5 to your computer and use it in GitHub Desktop.
Repository impl helper(with Realm, Future)
@_exported import class BrightFutures.Future
import func BrightFutures.future
import var BrightFutures.ImmediateOnMainExecutionContext
import RealmSwift
protocol RepositoryImplType {
func runWrite(f: (Realm) throws -> Void) -> Future<Void, RepositoryError>
func runRead<T>(f: (Realm) throws -> T) -> Future<T, RepositoryError>
func runReadAndBlock<T>(f: (Realm) throws -> T) throws -> T
func runWriteAndBlock(f: (Realm) throws -> Void) throws -> Void
}
extension RepositoryImplType {
func runWrite(f: (Realm) throws -> Void) -> Future<Void, RepositoryError> {
return future(context: RealmIOContext, task: {
let realm = RealmInstanceManager.sharedManager.realm()
do {
realm.beginWrite()
try f(realm)
try realm.commitWrite()
return .Success()
} catch {
realm.cancelWrite()
return .Failure(.IOException(reason: "", error: error as NSError)) // TODO
}
}).map(ImmediateOnMainExecutionContext, f: { $0 })
}
func runRead<T>(f: (Realm) throws -> T) -> Future<T, RepositoryError> {
return future(context: RealmIOContext, task: {
let realm = RealmInstanceManager.sharedManager.realm()
do {
let res = try f(realm)
return .Success(res)
} catch {
return .Failure(.IOException(reason: "", error: error as NSError)) // TODO
}
}).map(ImmediateOnMainExecutionContext, f: { $0 })
}
func runReadAndBlock<T>(f: (Realm) throws -> T) throws -> T {
let realm = RealmInstanceManager.sharedManager.realm()
return try f(realm)
}
func runWriteAndBlock(f: (Realm) throws -> Void) throws -> Void {
let realm = RealmInstanceManager.sharedManager.realm()
do {
realm.beginWrite()
try f(realm)
try realm.commitWrite()
} catch {
realm.cancelWrite()
throw RepositoryError.IOException(reason: "", error: error as NSError) // TODO
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment