@@ -2,22 +2,34 @@ import Foundation
22import SwiftUI
33
44public class LocalDataStore : ObservableObject , PersistentDataStore {
5+ public static let shared = LocalDataStore ( )
6+
57 @Published public private( set) var favorites : [ SubredditSmall ] = [ ] {
68 didSet {
7- persistData ( data: SavedData ( favorites: favorites) )
9+ saveData ( )
10+ }
11+ }
12+
13+ @Published public private( set) var recentlyVisited : [ SubredditSmall ] = [ ] {
14+ didSet {
15+ saveData ( )
816 }
917 }
1018
1119 let persistedDataFilename = " redditOsData "
1220 typealias DataType = SavedData
21+
1322 struct SavedData : Codable {
1423 let favorites : [ SubredditSmall ]
24+ let recentlyVisited : [ SubredditSmall ] ?
1525 }
1626
1727 public init ( ) {
18- var favorites = restorePersistedData ( ) ? . favorites ?? [ ]
28+ let data = restorePersistedData ( )
29+ var favorites = data? . favorites ?? [ ]
1930 favorites. sort { $0. name. lowercased ( ) < $1. name. lowercased ( ) }
2031 self . favorites = favorites
32+ self . recentlyVisited = data? . recentlyVisited ?? [ ]
2133 }
2234
2335 // MARK: - Favorites management
@@ -27,11 +39,29 @@ public class LocalDataStore: ObservableObject, PersistentDataStore {
2739 }
2840 }
2941
42+ public func add( recent: SubredditSmall ) {
43+ guard !recentlyVisited. contains ( recent) else {
44+ return
45+ }
46+ var edit = recentlyVisited
47+ edit. insert ( recent, at: 0 )
48+ if edit. count > 5 {
49+ edit. removeLast ( )
50+ }
51+ recentlyVisited = edit
52+ }
53+
3054 public func remove( favorite: SubredditSmall ) {
3155 favorites. removeAll ( where: { $0 == favorite } )
3256 }
3357
3458 public func remove( favoriteNamed: String ) {
3559 favorites. removeAll ( where: { $0. name == favoriteNamed } )
3660 }
61+
62+ // MARK: - Private
63+
64+ private func saveData( ) {
65+ persistData ( data: SavedData ( favorites: favorites, recentlyVisited: recentlyVisited) )
66+ }
3767}
0 commit comments