RxJava 根据条件从项目中删除重复项

RxJava remove duplicates from items based on criteria

在我的项目中,我从 XML 报告中检索操作列表并将新操作上传到 Firebase。 这工作正常:

//Go through de XML report emitting one node each time
Observable.merge(
    Observable.fromIterable(XML.convertToIterable(xmlReport.getElementsByTagName(IBConstants.CashTransactionNode))),
    Observable.fromIterable(XML.convertToIterable(xmlReport.getElementsByTagName(IBConstants.TradeNode))))
        .flatMap((Function<Node, ObservableSource<iIB>>) node ->

//For each XML node, convert it to the appropriate object (cashTransaction or Trade)
//I'm not interested on CashTransactions of type 'Other_fees' with description containing 'CONSOLIDATED SNAPSHOTS'
Observable.just(XML.getObjectFromXMLNode(node)))
    .filter(iIBTransaction -> !iIBTransaction.getDescription().contains(CashTransaction.OtherFees_filter))
    .flatMap((Function<iIB, ObservableSource<iIB>>) iIBTransaction ->

//Check if the new object already exists in Firebase (check transactionID)
//checkIfNewOperation returns new CashTransaction with all values to null if already exists so only new operations pass filter iIBTransaction.getTransactionID() != null
FirebaseClass.getInstance().checkIfNewOperation(iIBTransaction))
        .filter(iIBTransaction -> iIBTransaction.getTransactionID() != null)

//Create a list with all elements passing filter and return it
        .toList()
        .flatMap((Function<List<iIB>, SingleSource<List<iIB>>>) Single::just));

至此,我有了所需的新操作。问题是我没有生成 XML 并且我注意到某些操作是重复的。 我想删除此操作,但我想根据我的标准确定两个操作是否相等。如果它们相等,我会将所有这些相等的操作组合成一个并让流程继续。

如有任何帮助,我们将不胜感激。

Distinct 适用于 Object.equalsObject.hashCode 比较,因此如果您的项目可以直接相互比较,请使用基本的 distinct() 运算符。

如果无法比较它们或者 Object.equals 对于此类检查不正确,您必须将每个项目投影到一个对象中,该对象实现了正确的 equalshashCode, 然后使用 distinct(Function).

// this is the non-equatable object you want to have distinct over
class MyObject {
   String value;
}

// this object provides proper equality checks
final class MyDistinctObject {

    final String value;

    MyDistinctObject(MyObject obj) {
        this.value = obj.value;
    }

    @Override public boolean equals(Object other) {
        if (other instanceof MyDistincObject) {
            return value.equals(((MyDistinctObject)other).value);
        }
        return false;
    }

    @Override public int hashCode() {
        return value.hashCode();
    }
}

// find the distinct elements of MyObjects based on the equality checks of the helper
sourceOfMyObjects.distinct(MyDistinctObject::new)