Combine a list of Observables and wait until all completed

前端 未结 8 1097
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-04 06:35

TL;DR How to convert Task.whenAll(List) into RxJava?

My existing code uses Bolts to build up a list of asynchr

8条回答
  •  旧时难觅i
    2020-12-04 06:55

    I had similar problem, I needed to fetch search items from rest call while also integrate saved suggestions from a RecentSearchProvider.AUTHORITY and combine them together to one unified list. I was trying to use @MyDogTom solution, unfortunately there is no Observable.from in RxJava. After some research I got a solution that worked for me.

     fun getSearchedResultsSuggestions(context : Context, query : String) : Single>>
    {
        val fetchedItems = ArrayList>>(0)
        fetchedItems.add(fetchSearchSuggestions(context,query).toObservable())
        fetchedItems.add(getSearchResults(query).toObservable())
    
        return Observable.fromArray(fetchedItems)
            .flatMapIterable { data->data }
            .flatMap {task -> task.observeOn(Schedulers.io())}
            .toList()
            .map { ArrayList(it) }
    }
    

    I created an observable from the array of observables that contains lists of suggestions and results from the internet depending on the query. After that you just go over those tasks with flatMapIterable and run them using flatmap, place the results in array, which can be later fetched into a recycle view.

提交回复
热议问题