Skip to content

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

Description

@ishkawa

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
    }
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions