CustomScheduler.swift 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. //
  2. // CustomScheduler.swift
  3. // Mastodon
  4. //
  5. // Created by MainasuK Cirno on 2021-4-30.
  6. //
  7. import Foundation
  8. import Combine
  9. // Ref: https://stackoverflow.com/a/59069315/3797903
  10. struct CustomScheduler: Scheduler {
  11. var runLoop: RunLoop
  12. var modes: [RunLoop.Mode] = [.default]
  13. func schedule(after date: RunLoop.SchedulerTimeType, interval: RunLoop.SchedulerTimeType.Stride,
  14. tolerance: RunLoop.SchedulerTimeType.Stride, options: Never?,
  15. _ action: @escaping () -> Void) -> Cancellable {
  16. let timer = Timer(fire: date.date, interval: interval.magnitude, repeats: true) { timer in
  17. action()
  18. }
  19. for mode in modes {
  20. runLoop.add(timer, forMode: mode)
  21. }
  22. return AnyCancellable {
  23. timer.invalidate()
  24. }
  25. }
  26. func schedule(after date: RunLoop.SchedulerTimeType, tolerance: RunLoop.SchedulerTimeType.Stride,
  27. options: Never?, _ action: @escaping () -> Void) {
  28. let timer = Timer(fire: date.date, interval: 0, repeats: false) { timer in
  29. timer.invalidate()
  30. action()
  31. }
  32. for mode in modes {
  33. runLoop.add(timer, forMode: mode)
  34. }
  35. }
  36. func schedule(options: Never?, _ action: @escaping () -> Void) {
  37. runLoop.perform(inModes: modes, block: action)
  38. }
  39. var now: RunLoop.SchedulerTimeType { RunLoop.SchedulerTimeType(Date()) }
  40. var minimumTolerance: RunLoop.SchedulerTimeType.Stride { RunLoop.SchedulerTimeType.Stride(0.1) }
  41. typealias SchedulerTimeType = RunLoop.SchedulerTimeType
  42. typealias SchedulerOptions = Never
  43. }