DIKit icon indicating copy to clipboard operation
DIKit copied to clipboard

Add Shared<T> to return shared instance in provider method

Open ishkawa opened this issue 6 years ago • 0 comments

Rough sketch:

final class Counter {
    var value = 0
}

protocol MyResolver: Resolver {
    // A MyResolver instance always returns the same instance of Counter. 
    func provideCounter() -> Shared<Counter>
}

// Generated code
extension MyResolver {
    func resolveCounter() -> Counter {
        final class Scope {
            // NOTE: WeakDictionary doesn't present in standard library.
            static var sharedInstances = [:] as WeakDictionary<MyResolver, Counter>
        }

        // Return shared instance associated with MyResolver instance if it presents.
        if let sharedInstance = Scope.sharedInstances[self] {
            return associatedObject
        }

        // If shared instance is not found, call provider method and save returned instance as a shared instance.
        let sharedInstance = provideCounter()
        Scope.sharedInstances[self] = sharedInstance
        return sharedInstance
    }
}

ishkawa avatar Nov 13 '17 16:11 ishkawa