如何检查在RxSwift一个ReplaySubject所有的历史价值?

问题描述 投票:1回答:1

我有一个简单的结构Foo

struct Foo {
    let bar: String
}

现在,我创建ReplaySubjects的无限Foo

let subject = ReplaySubject<Foo>.createUnbounded()

我怎么能现在明白了(无端接)流是否具有Foobar等于abc? (这可能是第一,第三,或20元件)。

rx-swift
1个回答
1
投票

首先,这是一种疯狂的请求。你不应该想着“什么”,其中Rx工作时。相反,你应该考虑一下什么是总是如此。你应该考虑不变量...

这就是说,下面的操作会发出索引你。由于主题是能够不断地发出事件,操作者设计的实时工作。它可以像这样使用:

let indexes = subject.indexOfElementSatisfying { $0.bar == "abc" }

这里是:

extension ObservableConvertibleType {

    /**
     Emits the index of all the values in the stream that satisfy the predicate.

     - parameter pred: The predicate that determines whether the value satisfies the condition
     - returns: An observable sequence of indexes to those elements.
     */
    func indexOfElementSatisfying(_ pred: @escaping (E) throws -> Bool) -> Observable<Int> {
        return asObservable()
            .enumerated()
            .filter { try pred($0.element) }
            .map { $0.index }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.