Real-time save design pattern

I use Realm in the application, and I try to abstract as much as possible so that in the future I can change the database providers without any significant changes.

This template worked well, although the following worries me.

  • Creates a new realm object every time overhead (My real understanding is that Realm objects are cached internally)?
  • Are there any problems with the way I use Realm?
  • Are there any better design patterns for my purpose?

    public struct BookDataLayer: BookDataLayerProvider {
    
    func isBookAvailable(bookIdentifier: String) throws -> Bool {
        let database = try getDatabase()
        return !database.objects(Book).filter("identifier = %@", bookIdentifier).isEmpty
    }
    
    func createOrUpdateBook(bookIdentifier: String, sortIndex: Int) throws {
        let book = Book()
        Book.bookIdentifier = bookIdentifier
        Book.sortIndex = sortIndex
        try create(book, update: true)
    }}
    
    protocol BookDataLayerProvider : DataAccessLayer {
      func isBookAvailable(bookIdentifier: String) throws -> Bool
      func createOrUpdateBook(bookIdentifier: String, sortIndex: Int) throws n} 
    
      extension DataAccessLayer {
    
    func getDatabase() throws -> Realm {
        do {
            let realm = try Realm()
            // Advance the transaction to the most recent state
            realm.refresh()
            return realm
        } catch {
            throw DataAccessError.DatastoreConnectionError
        }
    }
    
    func create(object: Object, update: Bool = false) throws {
        let database = try self.getDatabase()
    
        do {
            database.beginWrite()
            database.add(object, update: update)
            // Commit the write transaction
            // to make this data available to other threads
            try database.commitWrite()
        } catch {
            throw DataAccessError.InsertError
        }
    }}
    
     // Usage
     let bookDataLayer = BookDataLayer()
     bookDataLayer.isBookAvailable("4557788")
    
     bookDataLayer.createOrUpdateBook("45578899", 10)
    
+4
source share
1 answer

This is a fully rugged construction. For developers, it is quite common to separate data-level APIs from their code if they need to disable it.

In answer to your questions:

  • . Realm , let realm = try! Realm() .
  • , , refresh() Realm , . Realm , refresh(), .
  • "" , , , , , , , !:)
+3

All Articles