繁体   English   中英

如何使用RxSwift处理应用程序状态

[英]How to handle application state with RxSwift

我是RxSwift的新手和RX的整个概念,我想知道如何处理由RxSwift从远程服务器获取的全局应用程序状态。

假设我需要获取JSON并将其解析为对象列表以在表视图中显示它,但我还需要以[{id: object}, ...]格式创建地图以使用应用程序其他部分中的数据。

例如:App重复从服务器获取人员列表,并且需要人员表视图的数据,以及人员消息以显示化身和具有相关消息的状态。 因此,由Person和Message模型组成的视图模型PersonViewModelMessageViewModel需要数据。

将是这种结构的正确方法:

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)
    }
}

并通过从服务器获取来调整应用程序状态:

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

并在viewModels中:

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

这是正确的方式还是存在一些不同的更好的方法? 我还想(将来)获取的数据仍然存在。 什么是最佳做法? 谢谢。

PS对不起代码中的拼写错误,如果有的话。 我只是编写而没有编译。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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