BirthdayViewModel.swift 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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 { return "NA" }
  26. let now = Date()
  27. let calendar = Calendar.autoupdatingCurrent
  28. let dayComps = calendar.dateComponents([.day], from: now, to: bday)
  29. guard let days = dayComps.day else { return "NA" }
  30. return String(days)
  31. }
  32. private var cancellable: AnyCancellable?
  33. private let birthdayLoader = BirthdayLoader()
  34. /// Fetches the birthday of the current user.
  35. func fetchBirthday() {
  36. birthdayLoader.birthdayPublisher { publisher in
  37. self.cancellable = publisher.sink { completion in
  38. switch completion {
  39. case .finished:
  40. break
  41. case .failure(let error):
  42. print("Error retrieving birthday: \(error)")
  43. }
  44. } receiveValue: { birthday in
  45. self.birthday = birthday
  46. }
  47. }
  48. }
  49. }