Last active
November 12, 2020 12:11
-
-
Save leovido/b5829a7a8c796cb57630aea3fab09385 to your computer and use it in GitHub Desktop.
Code to pick a random winner for the "Practical Combine" book by Donny Wals written in Combine; this is a giveaway from Twitter user: @onurgenes
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
import Combine | |
typealias TwitterUserName = String | |
enum BookGiveawayError: Error { | |
case noUserCommented | |
} | |
final class BookGiveaway: ObservableObject { | |
@Published var onDecisionTriggered = PassthroughSubject<Void, Error>() | |
let twitterUsers: [TwitterUserName] | |
var cancellable: AnyCancellable? | |
init(twitterUsers: [TwitterUserName]) { | |
self.twitterUsers = twitterUsers | |
cancellable = $onDecisionTriggered | |
.tryMap { _ -> TwitterUserName in | |
guard let bookWinner = self.twitterUsers.randomElement() else { | |
throw BookGiveawayError.noUserCommented | |
} | |
return bookWinner | |
} | |
.mapError({ $0 }) | |
.sink(receiveCompletion: { error in | |
print(error) | |
}, receiveValue: { bookWinner in | |
print(#"Congratulations \#(bookWinner)! You won a free copy of the "Practical Combine" book by @DonnyWals!"#) | |
}) | |
} | |
} | |
private func loadUsersWhoCommented() -> [TwitterUserName] { | |
[ /* List of all the users who commented on @onurgenes's tweet */ ] | |
} | |
let bg = BookGiveaway(twitterUsers: loadUsersWhoCommented()) | |
let signal: Void = Void() | |
bg.onDecisionTriggered.send(signal) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment