RxJava - How to take the first element of a list and return it as Observable

北慕城南 提交于 2019-12-10 15:28:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!