Reputation: 6073
I'm trying to turn this into an Observable without having an external variable or extra classes. Is this possible? It's a basic search through a list:
//...
for(int i = 0; i < items.size(); i++) {
if(items.get(i).id == findId) return i;
}
return -1;
So basically I have a string id which if I find I'd like to return the item index in the "items" list.
Upvotes: 2
Views: 4671
Reputation: 51
I am aware that this is an old question, but maybe someone will come in handy my solution using a helper class. It's a much more flexible, consistent and declarative way to do so. Any finite Observables are supported. Example:
Single<Integer> result = Observable.fromIterable(items)
.as(IndexedValue.firstMatch(next -> next.id == findId))
.map(IndexedValue::index)
.toSingle(-1);
Upvotes: 1
Reputation: 2247
One way to go is to use fromCallable
method to create an Observable
:
Observable.fromCallable(() -> {
for(int i = 0; i < items.size(); i++) {
if(items.get(i).id == findId) return i;
}
return -1;
});
or more declarative approach:
Observable.from(items)
.filter(item -> item.id == findId)
.map(items::indexOf);
Upvotes: 1
Reputation: 1960
One "neat" way of doing this without additional traverses overhead is as follows:
Observable<Integer> index = Observable.from(items)
.takeWhile(item -> item.id != findId)
.count()
.map(count -> count == data.size() ? -1 : count);
But i would stick to non-Rx approach for such simple use cases
Upvotes: 6