4

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.

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 [{id: object}, ...] to use the data in other sections of application.

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 PersonViewModel and MessageViewModel composed by models Person and Message.

Would be the correct way to have such structure:

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<PeopleStore>

    init(peopleStore: PeopleStore) {
        self.rx_peopleStore = Variable(peopleStore)
    }
}

And to adjust the app state by fetch from server:

...
_ = PeopleApi
    .rx_peopleStore
    .asDriver(onErrorJustReturn: [])
    .driveNext { peopleStore in
        sharedAppState.rx_peopleStore.value = peopleStore
    }
...

And in viewModels:

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

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.S. sorry for typos in code, if are there. I just wrote it without compiling.

solidcell
  • 7,067
  • 3
  • 34
  • 56

1 Answers1

0

I had a similar problem with keeping recent state of different things (like server responses, geolocation, etc.) and eventually made a lightweight Rx-based framework for this which I am using ever since, have a look whether it suits your needs as well - https://github.com/maxvol/RaspSwift

Maxim Volgin
  • 3,454
  • 1
  • 19
  • 30