sadat
sadat

Reputation: 4342

Perform a task for all items in a list and then perform another task in RxJava

Unfortunately, my REST Delete operation work only for one item. So what I was trying to do is,

Observable.just(items).flatMapIterable { items -> items }.flatMap {
                //call REST DELETE for every item
            }.flatMap {
                // call REST GET
            }

The problem is the GET call is being called for every item. How can I wait for finishing all the delete done and then perform the GET call?

Thanks in Advance.

Upvotes: 1

Views: 717

Answers (3)

taha
taha

Reputation: 771

Observable.just("one", "two", "three", "four", "five").subscribe(new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                Log.d("ffff", s);//print: one, two, three, four, five
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {

            }
        }, new Action() {
            @Override
            public void run() throws Exception {
                Log.d("ffff", "complete");//print: complete
            }
        });

Upvotes: 0

Bach Vu
Bach Vu

Reputation: 2348

In your case, you can apply toList() like this

fun doTask(items: List<String>):Observable<Boolean>{
        return Observable.fromIterable(items)
                .flatMap { processItem(it) }
                .toList()
                .toObservable()
                .flatMap { finalTask() }
    }

Upvotes: 1

sadat
sadat

Reputation: 4342

The problem can be solved with zip. In case any wants this

fun doTask(items: ArrayList<String>): Observable<Boolean> {
    val list = arrayListOf<Observable<String>>()
    items.forEach {
        list.add(processItem(it))
    }
    return Observable.zip(list) {
    }.flatMap {
        finalTask()
    }
}

fun processItem(s: String): Observable<String> {
    print(s)
    return Observable.just(s.toUpperCase())
}

fun finalTask(): Observable<Boolean> {
    print("final")
    return Observable.fromCallable { true }
}

Upvotes: 0

Related Questions