Search code examples
iosjsonswiftrx-swift

Does this Rx code subscribe to the changes of the JSON itself?


I have successfully parsed JSON data using URLSession. The data is then passed to an Rx sequence and finally the data is bound to a tableView. Now, my question is, is the JSON data itself observed? I mean, if there are changes in the remote JSON data, will my subscriber trigger? I'm guessing no, and that you need to somehow wrap the URLSession in an observer as well. But how would I go about doing that? Anyway, here's the code:

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

And in 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)

There's the structs for the parsed data as well, but no need to show them I guess.


Solution

  • Is the JSON data itself observed?

    A stored property parsedJson has a type Observable so, yes it's observable. You can modify the parsedJson stored property multiple times and resubscribe as well. You can do it for example when a user tap a button to refresh a datasource.

    If there are changes in the remote JSON data, will my subscriber trigger?

    No. To be informed about changes you have to trigger a getJSON method by your self in code or via timer or use a web socket dataTask instead a Http protocol. Important: The web socket protocol must enabled on a server side before using a web socket data task.