Created
May 30, 2016 02:14
-
-
Save ukitaka/bed11d8c874f4b4f5c467a322ad5eed5 to your computer and use it in GitHub Desktop.
Repository impl helper(with Realm, Future)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@_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