Skip to content

Commit

Permalink
Add whereType operator and tests.
Browse files Browse the repository at this point in the history
  • Loading branch information
renggli committed Aug 13, 2019
1 parent f94a953 commit 84e7d4d
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/operators.dart
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,4 @@ export 'src/operators/timeout.dart';
export 'src/operators/to_list.dart';
export 'src/operators/to_set.dart';
export 'src/operators/where.dart';
export 'src/operators/where_type.dart';
22 changes: 22 additions & 0 deletions lib/src/operators/where_type.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
library rx.operators.where_type;

import 'package:rx/src/core/observer.dart';
import 'package:rx/src/core/operator.dart';
import 'package:rx/src/core/subscriber.dart';

/// Filter items emitted by the source Observable by only emitting those that
/// are of the specified type.
OperatorFunction<T, R> whereType<T, R>() =>
(source) => source.lift<R>((source, subscriber) =>
source.subscribe(_WhereTypeSubscriber<T, R>(subscriber)));

class _WhereTypeSubscriber<T, R> extends Subscriber<T> {
_WhereTypeSubscriber(Observer<R> destination) : super(destination);

@override
void onNext(T value) {
if (value is R) {
doNext(value);
}
}
}
18 changes: 18 additions & 0 deletions test/operators_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1971,4 +1971,22 @@ void main() {
expect(actual, scheduler.isObservable('--#'));
});
});
group('whereType', () {
const values = {'x': 1};
test('first value filterd', () {
final input = scheduler.cold<Object>('--x--a--|', values: values);
final actual = input.pipe(whereType<Object, String>());
expect(actual, scheduler.isObservable<String>('-----a--|'));
});
test('second value filtered', () {
final input = scheduler.cold<Object>('--a--x--|', values: values);
final actual = input.pipe(whereType<Object, String>());
expect(actual, scheduler.isObservable<String>('--a-----|'));
});
test('second value filtered and error', () {
final input = scheduler.cold<Object>('--a--x--#', values: values);
final actual = input.pipe(whereType<Object, String>());
expect(actual, scheduler.isObservable<String>('--a-----#'));
});
});
}

0 comments on commit 84e7d4d

Please sign in to comment.