问题
Let's take this observable:
Observable<List<UserProfile>> findUser =service.getUserProfiles()
How can I transform it so it returns the first element as an Observable (and not an Observable list just containing the first element). I tried first() and takeFirst() but it still returns a list.
回答1:
Map it!
Observable<List<UserProfile>> findUser = service.getUserProfiles();
Observable<UserProfile> firstUser = findUser
.filter(list -> !list.isEmpty())
.map(list -> list.get(0));
回答2:
Without see what´s going on getUserProfile() it´s complicated, but what about this
@Test
public void getFirstUser(){
Observable<List<Integer>> findUser =Observable.just(Arrays.asList(1,2,3));
Observable<Integer> user = findUser
.flatMap(Observable::from)
.first();
user.subscribe(System.out::println);
}
来源:https://stackoverflow.com/questions/38212442/rxjava-how-to-take-the-first-element-of-a-list-and-return-it-as-observable