Is there a possibility to emit item that meets condition in takeUntil
operator?
Asked
Active
Viewed 8,176 times
3 Answers
10
Mmmm not sure if I understand your question. Something like this?
@Test
public void tesTakeUntil() {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
Observable.from(numbers)
.takeUntil(number -> number > 3)
.subscribe(System.out::println);
}
it will print
1
2
3
4
You can see more examples of Take here https://github.com/politrons/reactive/blob/master/src/test/java/rx/observables/filtering/ObservableTake.java

paul
- 12,873
- 23
- 91
- 153
-
Let's say I have `Observable
` and I have `.takeUntil("foo".equals(myString))` and I would like to get this last emitted item. – pixel Jul 04 '16 at 15:36 -
Then I would use .filter(s->s.equals("foo") I think is better if you provide your code to understand what do you want to do – paul Jul 04 '16 at 16:26
9
With this solution, the predicate only has to be called once.
final String stop = "c";
Observable.just("a", "b", "c", "d")
.takeUntil(item -> item.equals(stop))
.lastElement()
.subscribe(System.out::println);
Output:
c

veyndan
- 382
- 5
- 9
6
final String stop = "c";
Observable.just("a", "b", "c", "d")
.filter(item -> !item.equals(stop))
.takeUntil(item -> item.equals(stop))
.subscribe(System.out::println);
Output:
c

yurgis
- 4,017
- 1
- 13
- 22
-
what if my logic is really involved and I don't want to repeat it twice? – dabluck Nov 01 '16 at 15:48
-
If you mean logic for filter and takeUntil, then encapsulate it in a boolean method and pass the item to it. – yurgis Nov 01 '16 at 15:52
-
but with this solution, you have to call that method twice and do all the work twice... – dabluck Nov 01 '16 at 16:26
-
2 options: 1) define a side effect like final AtomicBoolean flag, set this flag before filter() with doOnNext(), then just get it in both filter and takeUntil; 2) pass boolean flag along with an item as a pair tuple. – yurgis Nov 02 '16 at 01:09