Advertisement
vmeansdev

Swift Loadable

Jun 12th, 2020
1,879
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.17 KB | None | 0 0
  1. // MARK: -
  2.  
  3. enum LoadingState: Equatable {
  4.  
  5.     case idle
  6.     case loading
  7.     case pulledToRefresh
  8.     case error(Error)
  9.  
  10. }
  11.  
  12. func ==(lhs: LoadingState, rhs: LoadingState) -> Bool {
  13.     switch (lhs, rhs) {
  14.     case (.idle, .idle):
  15.         return true
  16.     case (.loading, .loading):
  17.         return true
  18.     case (.pulledToRefresh, .pulledToRefresh):
  19.         return true
  20.     default:
  21.         return false
  22.     }
  23. }
  24.  
  25. // MARK: -
  26.  
  27. protocol LoadableState {
  28.  
  29.     var loadingState: LoadingState { get }
  30.  
  31.     var hasData: Bool { get }
  32.  
  33. }
  34.  
  35. // MARK: -
  36.  
  37. protocol Reloadable: class {
  38.  
  39.     @discardableResult func reload() -> Bool
  40.  
  41. }
  42.  
  43. // MARK: -
  44.  
  45. protocol Loadable: Reloadable {
  46.  
  47.     // MARK: Required Protocol
  48.  
  49.     associatedtype State: LoadableState
  50.  
  51.     var state: ReadOnlyVariable<State> { get }
  52.  
  53.     // MARK: Protocol with Default Implementation
  54.  
  55.     @discardableResult func pulledToRefresh() -> Bool
  56.  
  57. }
  58.  
  59. // MARK: -
  60.  
  61. extension Loadable {
  62.  
  63.     @discardableResult func pulledToRefresh() -> Bool {
  64.         return reload()
  65.     }
  66.  
  67.     @discardableResult func reloadIfNeeded() -> Bool {
  68.         return !state.value.hasData ? reload() : false
  69.     }
  70.  
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement