RxJava: How to convert List of objects to List of another objects

后端 未结 9 737
悲哀的现实
悲哀的现实 2021-01-31 07:30

I have the List of SourceObjects and I need to convert it to the List of ResultObjects.

I can fetch one object to another using method of ResultObject:

c         


        
9条回答
  •  北荒
    北荒 (楼主)
    2021-01-31 07:44

    If you want to maintain the Lists emitted by the source Observable but convert the contents, i.e. Observable> to Observable>, you can do something like this:

    Observable> source = ...
    source.flatMap(list ->
            Observable.fromIterable(list)
                .map(item -> new ResultsObject().convertFromSource(item))
                .toList()
                .toObservable() // Required for RxJava 2.x
        )
        .subscribe(resultsList -> ...);
    

    This ensures a couple of things:

    • The number of Lists emitted by the Observable is maintained. i.e. if the source emits 3 lists, there will be 3 transformed lists on the other end
    • Using Observable.fromIterable() will ensure the inner Observable terminates so that toList() can be used

提交回复
热议问题