简体   繁体   中英

How to handle application state with RxSwift

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.

PS sorry for typos in code, if are there. I just wrote it without compiling.

我有一个类似的问题,保持最近状态的不同事情(如服务器响应,地理位置等),并最终为此我做了一个轻量级的基于Rx的框架,从那以后,看看它是否也适合你的需求- https://github.com/maxvol/RaspSwift

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM