https://github.com/happn-app/semisingleton
Simple thread-safe uniquing of objects. Used by URLRequestOperation
https://github.com/happn-app/semisingleton
deprecated happsight library
Last synced: 4 months ago
JSON representation
Simple thread-safe uniquing of objects. Used by URLRequestOperation
- Host: GitHub
- URL: https://github.com/happn-app/semisingleton
- Owner: happn-app
- License: apache-2.0
- Created: 2018-01-20T13:42:15.000Z (over 8 years ago)
- Default Branch: main
- Last Pushed: 2023-11-17T13:05:09.000Z (over 2 years ago)
- Last Synced: 2026-01-11T05:27:52.017Z (6 months ago)
- Topics: deprecated, happsight, library
- Language: Swift
- Homepage:
- Size: 74.2 KB
- Stars: 2
- Watchers: 3
- Forks: 1
- Open Issues: 1
-
Metadata Files:
- Readme: Readme.md
- License: License.txt
Awesome Lists containing this project
README
# Semi-Singleton
 [](https://swift.org/package-manager/) [](License.txt) [](https://happn.com)
## What is a Semi-Singleton?
You all know the Singleton pattern.
A Semi-Singleton will be an object that will be returned as an already existing instance or a new one depending on whether there was already an instance in memory for the given id.
Here’s an example of a lifecycle of a Semi-Singleton object:
- A first client (`client1`) requests a semi-singleton object with id `obj`. Such an object does not already exists: it is instantiated. `client1` keeps a strong reference to this object for now.
- A second client (`client2`) requests a semi-singleton object with id `obj`. As the object already exists in memory, the same instance `client1` uses is returned.
- Both `client1` and `client2` release the semi-singleton they share. It is fully deallocated.
- A third client requests a semi-singleton object with id `obj`. As the previous semi-singleton with this id does not exist anymore, a new object is instantiated.
In code, a Semi-Singleton is any object conforming to the `SemiSingleton` or `SemiSingletonWithFallibleInit` protocol.
## How to use a Semi-Singleton?
```swift
/* First you need a “Store” that will hold the reference to the existing semi-singletons. */
let semiSingletonStore = SemiSingletonStore(forceClassInKeys: true)
/* To retrieve a semi-singleton instance, you ask the store to give you one. */
let s: MySemiSingleton = semiSingletonStore.semiSingleton(forKey: key)
```
## Use case
For instance, an “Action” object, when care should be taken that only one action run at the same time for the same subject.
The subject would be the Semi-Singleton key.
When the action is instantiated, if there is already an action in progress for the given subject, the already existing action will be returned, otherwise a new one is created.
## Credits
This project was originally created by [François Lamboley](https://github.com/Frizlab) while working at [happn](https://happn.com).