How to handle the first n elements and stay different in the observed stream

eg,

given a stream of a certain number (m) of numbers (m1, m2, m3, m4, m5, m6 ...) and apply the transformation (2 * i) to the first n elements (n can be less, equal to or greater than m), apply another transformation (3 * i) to the rest of the elements. and

Return result: m1 * 2, m2 * 2, m3 * 3, m4 * 3, m5 * 3, m6 * 3 ... (assuming n = 2 here).

I tried to use take (n) and skip (n) and then concatwith, but it looks like this: take (n) discards the remaining elements in the sequence and does skip (n) after that returns nothing.

0
source share
1 answer

m, take() skip(), - :

    int m = 10;
    int n = 8;
    Observable<Integer> numbersStream = Observable.just(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
            .publish();

    Observable<Integer> firstNItemsStream = numbersStream.take(n)
            .map(i -> i * 2);

    Observable<Integer> remainingItemsStream = numbersStream.skip(n)
            .map(i -> i * 3);

    Observable.merge(firstNItemsStream, remainingItemsStream)
            .subscribe(integer -> System.out.println("result = " + integer));
    numbersStream.connect();

EDIT:
@A.E. Daphne, share() , , /s, Observable /s, :
cache() - , , , , . reply().refCount() - Observable, reply() ( ), , .

, Observable .

publish(). publish() ConnectableObservable connect() , , , .

+2

Source: https://habr.com/ru/post/1674707/


All Articles