Using RxJs groupBy with objects as keys

I am trying to use groupBywith RxJs and I need to use objects as keys. If I do not, and I use, for example, simple strings like this:

var types = stream.groupBy(
    function (e) { return e.x; }); //x is a string

then everything will be fine, and my subscription is called once and once for each other key. But if I try to use objects, the subscription is called for each item from stream, even if the key turns out to be the same as the previous ones.

Of course, there is a problem with equality of objects, but I am embarrassed because I do not understand how to use additional arguments for groupBy. The latest version of the docs says that there is a third argument that can be a comparator, but it is never called. Earlier, docs talked about a key serializer, which is a completely different idea, but none of the methods work for me.

Having looked at the source code of Rx, I see attempts to test the function getHashCode, but I cannot find and document it. Code like this:

var types = stream.groupBy(
    function (e) {
        return { x: e.x, y: e.y };   //is this valid at all?
    },
    function (e) { return e; },
    function (...) { return ???; }); //what am I supposed to do here?

- this is what I'm trying to write, but not luck, and everything that I set for the third callback is not called.

What is wrong here?

+4
source share
1 answer

- , . , comparer hashCode, groupBy. hashCode ( ), valueOf, .

hashCode valueOf # Object.GetHashCode.

, :

  • , , .
  • , , ( ). , .

hashCode , valueOf . , valueOf .

comparer , 2 true false .

, :

var valueOf = function () {
    return JSON.stringify(this);
};

var keyCompare = function (a, b) { return a.x === b.x && a.y === b.y; };

var types = stream.groupBy(
    function (e) {
        return { x: e.x, y: e.y, valueOf: valueOf };   //is this valid at all?
    },
    function (e) { return e; },
    keyCompare);

valueOf , , , , string :

var types = stream.groupBy(
    function (e) { return JSON.stringify({ x: e.x, y: e.y }); },
    function (e) { return e; });
+2

All Articles