royhsu / tiny-kit

MIT License
12 stars 3 forks source link

[Feature] Storage #47

Open royhsu opened 6 years ago

royhsu commented 6 years ago

protocol Storage: Collection {

    var changes:  Observable<Changes> { get }

    var isLoaded: Bool { get }

    subscript(key: Key) -> Value?

    func load()

}

protocol AsyncStorage: Storage {

    func value(
        forKey key: Key,
        completion: (Result<Value>) -> Void
    )

}

protocol MutableStorage: Storage {

    func merge(_ other: Sequence)

}

concrete SyncStorage: MutableStorage {

    func addChild(_ storage: Storage) { 

        storage.changes.observe { child in

            self.merge(child)

        } 

    }

    subscript(key: Key) -> Value? {

        for child in childStorages {

            if let value = child[key] { return value }

        }

        asynchronouslyGettingValueFromChildStoragesIfNeeded()

    }

}
royhsu commented 6 years ago

The updating strategy is like how CoreData does.

  1. Parent observes changes from children.
  2. Merge changes if that happens.
  3. Forwarding all merged changes to outside.