Monday, 3 December 2018

Chain completation sync and async

I have a list of completables that by default I run them one after one with concat/andThen operators. Sometimes I want some part of the completables to run in parallel and after everything complete continue to the next completable in the list. I tried to achieve that with this code:

    var completable =
            getAsyncCompletables()?.let {
                it
            } ?: run {
                completables.removeAt(0).getCompletable()
            }
        while (completables.isNotEmpty()) {
            val nextCompletable = getAsyncCompletables()?.let {
                it
            } ?: run {
                completables.removeAt(0).getCompletable()
            }
            completable = nextCompletable.startWith(completable)
        }
        completable
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(AndroidSchedulers.mainThread())
            .subscribe()

I use this code to detect the async completables:

 private fun getAsyncCompletables(): Completable? {
    if (completables.size < 2 || !completables[1].async) {
        return null
    }
    var completable = completables.removeAt(0).getCompletable()
    while (completables.isNotEmpty() && completables[0].async) {
        completable = completable.mergeWith(completables.removeAt(0).getCompletable())
    }
    return completable
}

All works fine, except one thing, the last completable not triggered althought I used "startWith". I also tried "concatWith" and "andThen",but same result.



from Chain completation sync and async

No comments:

Post a Comment