BirthdayViewModel.swift 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*
  2. * Copyright 2021 Google LLC
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import Combine
  17. import Foundation
  18. /// An observable class representing the current user's `Birthday` and the number of days until that date.
  19. final class BirthdayViewModel: ObservableObject {
  20. /// The `Birthday` of the current user.
  21. /// - note: Changes to this property will be published to observers.
  22. @Published private(set) var birthday: Birthday?
  23. /// Computed property calculating the number of days until the current user's birthday.
  24. var daysUntilBirthday: String {
  25. guard let bday = birthday?.date else {
  26. return NSLocalizedString("No birthday", comment: "User has no birthday")
  27. }
  28. let now = Date()
  29. let calendar = Calendar.autoupdatingCurrent
  30. let dayComps = calendar.dateComponents([.day], from: now, to: bday)
  31. guard let days = dayComps.day else {
  32. return NSLocalizedString("No birthday", comment: "User has no birthday")
  33. }
  34. return String(days)
  35. }
  36. private var cancellable: AnyCancellable?
  37. private let birthdayLoader = BirthdayLoader()
  38. /// Fetches the birthday of the current user.
  39. func fetchBirthday() {
  40. birthdayLoader.birthdayPublisher { publisher in
  41. self.cancellable = publisher.sink { completion in
  42. switch completion {
  43. case .finished:
  44. break
  45. case .failure(let error):
  46. self.birthday = Birthday.noBirthday
  47. print("Error retrieving birthday: \(error)")
  48. }
  49. } receiveValue: { birthday in
  50. self.birthday = birthday
  51. }
  52. }
  53. }
  54. }