rxdart
rxdart copied to clipboard
DistinctUnique does not filter unique string when 'equals' parameter is provided
Stream.fromIterable(['Alpha', 'Beta', 'Gamma']).distinctUnique( equals: (e1, e2) { return e1.length == e2.length; }).listen((event) { print(event); });
The output is : Alpha beta Gamma
Expected Output: Since distinceUnique is performing equality based on length of string, the output should be 'Alpha beta' only.
There is no difference in functionality in 'distinctUnique' and 'distinct' when parameter is provided.
Version: 0.24.1
DistinctUnique uses a HashSet underneath, alpha and gamma aren't the same hashCode, so you'd need to provide a different hashing method, next to the equals handler.
For example (e) => e.length
...that said maybe we could just do without the hassle of needing a hasher, and just require an equals only
@Santosh07 HashSet
checks two instance are the same hashCode
before calling equals
. You can write distinctUniqueBy
extensions method:
extension DistinctUniqueExtension<T> on Stream<T> {
/// WARNING: More commonly known as distinct in other Rx implementations.
///
/// Creates a Stream where data events are skipped if they have already
/// been emitted before, based on [hashCode] and [equals] comparison of the objects
/// returned by the key selector function.
///
/// Equality is determined by the provided equals and hashCode methods.
/// If these are omitted, the '==' operator and hashCode on the last provided
/// data element are used.
///
/// The returned stream is a broadcast stream if this stream is. If a
/// broadcast stream is listened to more than once, each subscription will
/// individually perform the equals and hashCode tests.
///
/// [Interactive marble diagram](http://rxmarbles.com/#distinct)
Stream<T> distinctUniqueBy<R>(
R Function(T) keySelector, {
bool Function(R e1, R e2) equals,
int Function(R e) hashCode,
}) =>
distinctUnique(
equals: (e1, e2) {
final k1 = keySelector(e1);
final k2 = keySelector(e2);
return equals?.call(k1, k2) ?? (k1 == k2);
},
hashCode: (e) {
final k = keySelector(e);
return hashCode?.call(k) ?? k.hashCode;
},
);
}
and use it
void main() {
Stream.fromIterable(['Alpha', 'Beta', 'Gamma'])
.distinctUniqueBy((e) => e.length)
.listen(print);
}
@frankpepermans Should add distinctUniqueBy
to rxdart
, related to #396
@hoc081098 Dunno if we should have both distinctUnique
and distinctUniqueBy
, I'd go for the easiest version here, which is distinctUniqueBy
, wdyt?
@frankpepermans I think we should keep both:
- if only keep
distinctUnique
, it's confusing like this issue. - if only keep
distinctUniqueBy
, it's quite verbose when writing like this:distinctUniqueBy((e) => e)
.
I have a another option: add selector
optional param to distinctUnique
. And if selector
is null, it's just identify function
, but we must cast T as R
😆
For anyone interested in distinctUniqueBy
, consider my package https://github.com/hoc081098/rxdart_ext 😃