ios - 这个 Rx 代码是否订阅了 JSON 本身的变化?

标签 ios json swift rx-swift

我已经使用 URLSession 成功解析了 JSON 数据。然后将数据传递给 Rx 序列,最后将数据绑定(bind)到 tableView。现在,我的问题是,JSON 数据本身是否被观察到?我的意思是,如果远程 JSON 数据发生变化,我的 subscriber 会触发吗?我猜不会,而且您还需要以某种方式将 URLSession 包装在观察者中。但是我该怎么做呢?无论如何,这是代码:

func getJSON() {
        guard let url = URL(string:"https://api.myjson.com/bins/sbmzi") else { return }

        URLSession.shared.dataTask(with: url) { data, response, error in
            guard let data = data else { return }
            do {
                let jsonDecoder = JSONDecoder()
                jsonDecoder.keyDecodingStrategy = .convertFromSnakeCase
                jsonDecoder.dateDecodingStrategy = .iso8601

                let decodedJson = try jsonDecoder.decode(People.self, from: data)
                self.parsedJson.accept(decodedJson.people)

            } catch {
                print(error)
            }
        }.resume()
    }

viewDidLoad 中:

getJSON()

        self.parsedJson.subscribe(onNext: {
            print("👀Observing👀")
            print($0.description)
        }).disposed(by: disposer)

        self.parsedJson.bind(to: myTableView.rx.items(cellIdentifier: "cell")) { row, data, cell in
            cell.textLabel?.text = "\(data.name), \(data.job), \(data.bestBook.title), \(data.bestBook.author.name)"
        }.disposed(by: disposer)

还有用于解析数据的结构,但我想不需要显示它们。

最佳答案

JSON数据本身是否被观察到?

一个存储属性 parsedJson 有一个类型 Observable 所以,是的,它是可观察的。您可以多次修改 parsedJson 存储属性并重新订阅。例如,当用户点击按钮刷新数据源时,您可以这样做。

如果远程 JSON 数据发生变化,我的订阅者会触发吗?

没有。要了解更改,您必须自己在代码中或通过计时器触发 getJSON 方法,或使用 web socket dataTask而是一个 Http 协议(protocol)。重要提示:在使用网络套接字数据任务之前,必须在服务器端启用网络套接字协议(protocol)。

关于ios - 这个 Rx 代码是否订阅了 JSON 本身的变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59766220/

相关文章:

Javascript 无法正确解析 JSON 中的对象

json - 类型错误 : Object of type 'complex' is not JSON serializable while using pyLDAvis. display() 函数

swift - 在 Swift 中创建一个带有背景的 UIView

ios - 自动创建 Xcode 项目 (.xcodeproj)

ios - 核心图 : Label in BarChart

jquery - 如何从客户端创建和发送 JSON

ios - 语义问题 : Cannot find the protocol declaration for ‘ARSessionDelegate’

ios - 如何连接来自 xib 中自定义类的委托(delegate)?

ios - SIGABRT错误-分段控制

ios - 尝试添加 UIImage 作为 Storyboard中的背景(不重叠我的其他 ViewController 元素)