Skip to content

Instantly share code, notes, and snippets.

@robertmryan
Created April 13, 2025 06:23
Show Gist options
  • Save robertmryan/def683141344e9d000c865e7765116b5 to your computer and use it in GitHub Desktop.
Save robertmryan/def683141344e9d000c865e7765116b5 to your computer and use it in GitHub Desktop.
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
}
}
@robertmryan
Copy link
Author

Also, while I was here, I'd recommend

  • giving your synchronization queue a meaningful name that captures the functional purpose of the queue; and
  • use if let tokenPub {…} and guard let self else { return } for more concise safe unwrapping of the optionals.

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