How to handle application state with RxSwift
<p>I am new to RxSwift and whole concept of RX and I would like to know how to handle global application state fetched from remote server by RxSwift.</p>

<p>Let's assume I need to fetch JSON and parse it to list of objects to show it in table view but also I need to create map in format <code>[{id: object}, ...]</code> to use the data in other sections of application.</p>

<p>For example: App repetitively fetches a person list from server and needs the data for person table view as for persons messages to display avatar and status with related message. So the data are needed for view models <code>PersonViewModel</code> and <code>MessageViewModel</code> composed by models Person and Message.</p>

<p>Would be the correct way to have such structure:</p>

<pre><code>struct Person {
    let id: personId
    let fullName: String
    let status: personStatus
}

class PeopleStore {
    var order: [personId] = []
    var dataMap: [personId: Person] = [:]

    init(people: [Person]) {
        order = people.map { $0.id }
        for person in people {
            dataMap[person.id] = person
        }
    }
}

class AppState {
    let rx_peopleStore: Variable&lt;PeopleStore&gt;

    init(peopleStore: PeopleStore) {
        self.rx_peopleStore = Variable(peopleStore)
    }
}
</code></pre>

<p>And to adjust the app state by fetch from server:</p>

<pre><code>...
_ = PeopleApi
    .rx_peopleStore
    .asDriver(onErrorJustReturn: [])
    .driveNext { peopleStore in
        sharedAppState.rx_peopleStore.value = peopleStore
    }
...
</code></pre>

<p>And in viewModels:</p>

<pre><code>...
_ = sharedAppState
    .rx_peopleStore
    .asDriver()
    .driveNext { store in
        // refreshUI by data from store
    }
    .addDisposableTo(bag)
...
</code></pre>

<p>Is this correct way or exists some different and better approach? I would like to also (in future) the fetched data persist. What is the best practice? Thank you.</p>

<p>P.S. sorry for typos in code, if are there. I just wrote it without compiling.</p>