无法将类型 [Employees] 的值分配给类型 'PublishSubject<[Employees]>

Cannot assign value of type [Employees] to type 'PublishSubject<[Employees]>

我已经使用 URLSession 成功 parsed json 数据,现在我想将 parsed 数据添加到 array。使用普通 array 可以正常工作,但我正在学习 Rx,因此想使用 subject

所以,这有效:

var parsedJson = [Employees]()
self.parsedJson = decodedJson.people

但这给出了一个错误:

var parsedJson: PublishSubject<[Employees]> = PublishSubject<[Employees]>()
self.parsedJson = decodedJson.people

Cannot assign value of type '[Employees]' to type 'PublishSubject<[Employees]>'

这里是 URLSession 代码:

//    var parsedJson = [Employees]()
    var parsedJson: PublishSubject<[Employees]> = PublishSubject<[Employees]>()


    func getJSON(completion: @escaping () -> Void) {
        guard let url = URL(string:"https://api.myjson.com/bins/jmos6") 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 = decodedJson.people
                completion()
            } catch {
                print(error)
            }
        }.resume()
    }

有谁知道如何做到这一点以及为什么首先会出现错误? <> 不是简单地表示哪个 type 应该是 observed 吗?也没有让 .accept() 工作。

编辑

let parsedJson: BehaviorRelay<[Employees]> = BehaviorRelay(value: [])
self.parsedJson.accept(decodedJson.people)

这行得通,但是 BehaviorSubjectPublishSubjuct 的等价物是什么?

尝试

self.parsedJSON.onNext(decodedJson.people)

错误信息非常清楚:您的类型不匹配。例如,如果您尝试将 String 分配给 Int 变量,您会收到相同的错误消息。 PublishSubject 不是数组。它是一种用于发送特定类型的值流(这里是员工数组)的机制(将其视为管道)。

您通常通过像这样订阅主题来使用它们:

var parsedJson = PublishSubject<[Employee]>()
// the 'next' block will fire every time an array of employees is sent through the pipeline
parsedJson.next { [weak self] employees in
    print(employees)
}

每次通过 PublishSubject 发送数组时,上面的 next 块都会触发,如下所示:

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

从您的编辑看来,您似乎继续尝试使用 BehaviorRelay。我建议先阅读这两个 类 之间的区别,然后再决定哪个适合您的用例。在尝试了解不同类型的主题和中继之间的差异时,这篇文章对我很有帮助:https://medium.com/@dimitriskalaitzidis/rxswift-subjects-a2c9ff32a185

祝你好运!