Home > Software engineering >  Should I put my UserDefaults saving process into ViewModel? (good architecture)
Should I put my UserDefaults saving process into ViewModel? (good architecture)

Time:02-10

I'm creating a simple NewsApp. I want to create the best app architecture I can made. So my question is that if I want save really simple data like username and maybe 5-6 tags as strings, should I put userDefaults logic into my viewModel or should I create a layer between ViewModel and UserDefaultsAPI which will take care about saving data?

I mean I will create StoreData protocol which UserDefaultsAPI will implement. And if I should do it how I can achieve that? I am using RxSwift and I don't now how to subscribe changing data in UserDefaults by UserDefaultsAPI.

CodePudding user response:

You should create a layer between, but given an Rx/functional architecture, it shouldn't be something heavy weight like a protocol.

Learn How to Control the World and do something like this instead:

struct Storage {
    static var shared = Storage()
    var saveProperty: (Property) -> Void = { property in
        UserDefaults.standard.set(try? JSONEncoder().encode(property), forKey: "property")
    }
    var deleteProperty: () -> Void = {
        UserDefaults.standard.removeObject(forKey: "property")
    }
    var currentProperty: () -> Observable<Property?> = {
        UserDefaults.standard.rx.observe(Data.self, "property")
            .map { $0.flatMap { try? JSONDecoder().decode(Property.self, from: $0) } }
            .distinctUntilChanged()
    }
}

struct Property: Codable, Equatable { }
  • Related