gpt4 book ai didi

swift - RxSwift - 如何连接集合的可观察对象

转载 作者:可可西里 更新时间:2023-11-01 01:56:40 25 4
gpt4 key购买 nike

我正在尝试使用 concat() 运算符连接两个集合的可观察对象,但是,它没有按预期工作。

我有两个可观察对象:

let first = Observable<[Int]>.create { observer in
observer.onNext([1, 2])
observer.onCompleted()
return Disposables.create()
}

let second = PublishSubject<[Int]>()

使用 concat():

let items = Observable.concat([first, second])

items.subscribe(onNext: {
print($0)
})

second.onNext([3, 4, 5])

输出:

[1, 2]
[3, 4, 5]

我想要的:

[1, 2]
[1, 2, 3, 4, 5]

最佳答案

所以您只是想要连接两个可观察对象,您想要连接两个可观察对象产生的事件中的数组。你走的还不够远,无法得到你想要的。

假设您有两个 Array<[Int]> 而不是两个 Observable<[Int]>。连接两者(如 arr1 + arr2)不会产生 [[1, 2], [1, 2, 3, 4, 5]],而是会产生 [[1, 2], [3, 4, 5]]。您的 Observables 的行为方式相同。

要同时连接 将它们组合起来,您需要 scan,如:

let items = Observable.concat([first, second])
.scan([], accumulator: +)

这将产生两个事件:

[1, 2]
[1, 2, 3, 4, 5]

仅供引用,对于数组,我们没有扫描运算符,但我们可以用 reduce 来近似它。对于数组,它将是:

let arr1: Array<[Int]> = [[1, 2]]
let arr2: Array<[Int]> = [[3, 4, 5]]
let itemsArr = (arr1 + arr2).reduce([], { result, element in
return result + [(result.last ?? []) + element]
})
print(itemsArr)

关于swift - RxSwift - 如何连接集合的可观察对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52794894/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com