stackotter/swift-cross-ui

Saving State between launches

Amzd opened this issue · 5 comments

Amzd commented

It would be nice to be able to save state between launches.

  • SavableAppState that conforms to Codable or
  • a Property wrapper for which parts of state should be saved?
  • Save location?
  • ?

I love that idea! That would be really useful. I’ll think about how that would best be done.

Do reckon we could possibly use GSettings? The persistent app state properties can just be converted to json and stored as a string in the settings.

My main reason for suggesting that is that it would solve the issue of having to figure out a good storage location for every different OS that SwiftCrossUI supports.

Alternatively we could probably just find where GSettings stores state on each OS and copy it (so that we're not forced to use their API).

And in terms of how to mark which properties are persistent, we could simplify that with something like this:

protocol AppState: ViewState {
    associatedtype PersistedState: Codable, ViewState

    @Observed
    var persisted: PersistedState
}

struct EmptyPersistedState: Codable {}

extension AppState where PersistedState == EmptyPersistedState {
    @Observed
    var persisted: EmptyPersistedState { EmptyPersistedState() }
}

That means that if someone wants to persist part of their app state they can implement the persisted property, and put all persisted state inside that.

I'm not sure if that code is actually valid, but it's at least close to what I have in mind, it may need some modification.

Amzd commented

GSettings sounds good!

associatedtype PersistedState: Codable, ViewState

I think currently @observed only works with value types and not reference types, which shouldn't be too hard to fix.

I think currently @observed only works with value types and not reference types, which shouldn't be too hard to fix.

Oh yeah, good catch. I can fix that pretty easily