wayfair / vsm-ios

An iOS framework for the VSM Architecture
MIT License
9 stars 2 forks source link

Added new method to StateContainer that takes a StateSequence instace #48

Closed bdunay3 closed 2 months ago

bdunay3 commented 3 months ago

Description

I've been using VSM more and more inside of Swift Concurrency code and notice that I keep repeating the same mistake over and over. When ever I write a function on a state model that returns a StateSequence, I mark that function as async even though inside said function I don't call any async functions. I believe it's because current the only way to have StateContainer to observe a StateSequence you need to call the observeAsync method which takes an async closure that returns a StateSequence.

Take this method as an example;

func getFirstPage(using datasource: Datasource) async -> StateSequence<PagedListViewState> {
    .init({ .fetchingFirstPage }, { await fetchingPage(using: datasource) })
}

I wrote it this way because when I call it I typically write it like this:

$state.observeAsync { await viewModel.getFirstPage(using: datasource) }

But this is entirely unnecessary because creating a new instance of StateSequence is not an async options. StateSequence models an array of async closures that return a State. iterating through the sequence is an async operation.

So in this PR I added a new overload to the observe method that I think is a better fit when you need to only observer a StateSequence, but creating that sequence is not asynchronous. Taking the same code as above I would now write the function that returns the StateSequence like this:

func getFirstPage(using datasource: Datasource) -> StateSequence<PagedListViewState> {
    .init({ .fetchingFirstPage }, { await fetchingPage(using: datasource) })
}

And when I go to observe those state changes I would call the new observe method that would look like this:

$state.observe(viewModel.getFirstPage(using: datasource))

I think this should prevent other users from making the same mistake I keep making.

Type of Change

Checklist

albertbori commented 2 months ago

Fantastic addition, Bill! Thanks!