Created
April 13, 2025 06:23
-
-
Save robertmryan/def683141344e9d000c865e7765116b5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private var tokenPub: AnyPublisher<String, Error>? // make this private to prevent unintended direct access to this publisher … you want to make sure that all access is via your private queue | |
private let tokenPubQueue = DispatchQueue( // make this `private`, as it is internal to this type | |
label: Bundle.main.bundleIdentifier! + ".tokenQueue" | |
) | |
func accessToken(refreshToken: String) -> AnyPublisher<String, Error> { | |
return tokenPubQueue.sync { | |
if let tokenPub { | |
return tokenPub | |
} | |
let publisher = API.client.publisher(refreshToken) | |
.receive(on: tokenPubQueue) | |
.handleEvents(receiveCompletion: { [weak self] completion in | |
guard let self else { return } | |
switch completion { | |
case .finished, .failure: | |
self.tokenPub = nil | |
} | |
}) | |
.share() | |
.eraseToAnyPublisher() | |
tokenPub = publisher | |
return publisher | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Also, while I was here, I'd recommend
if let tokenPub {…}
andguard let self else { return }
for more concise safe unwrapping of the optionals.