Last active
March 24, 2021 19:26
-
-
Save andreacipriani/b4fe84acdd68a0a9ab3b81a1b960fd3f to your computer and use it in GitHub Desktop.
An example that shows how to map a publisher with an asynchronous function, using DispatchGroup
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
func makeUppercase(_ string: String, completion: (String) -> Void) { | |
sleep(2) | |
completion(string.uppercased()) | |
} | |
let subject = CurrentValueSubject<String, Never>("foo") | |
let publisher = subject.eraseToAnyPublisher() | |
let group = DispatchGroup() | |
let mappedPublisher = publisher.map { string -> String in | |
var uppercase: String = string | |
group.enter() | |
makeUppercase(string) { uppercaseString in | |
uppercase = uppercaseString | |
group.leave() | |
} | |
group.wait() | |
return uppercase | |
} | |
mappedPublisher.sink { value in | |
print(value) | |
} | |
subject.send("bar") | |
print("done") | |
/// The program prints: | |
/// FOO | |
/// BAR | |
/// done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment