Mikhail
Mikhail

Reputation: 3746

Rx Java subscribe only to one item emitted

I have a BehaviorSubject data that contains actual data (or maybe nothing, if nothing has been emitted to it). I want to subscribe for only one item it emits, i.e. either the current observed value or the first to be passed to it from somewhere else. I'm currently doing it the following way:

Subscription firstItemSubscription = data.subscribe(item -> {
    firstItemSubscription.unsubscribe();
    processItem(item);
});

Is there any operator or transformer that I could use instead? Or probably there is completely different, more Rx approach that would allow me to do the thing I want to?

Upvotes: 2

Views: 2380

Answers (1)

cyroxis
cyroxis

Reputation: 3711

Yes use just need to use take(1)

Observable observable = //some observable

observable.take(1).subscribe(/* do your thing */);

Upvotes: 8

Related Questions