https://kotlinlang.org logo
#coroutines
Title
# coroutines
t

Timur Atakishiev

01/28/2020, 10:04 AM
Copy code
someList.forEach {
    GlobalScope.launch {
        if (validator.validate(it)){
            someStorage.add(it)
        }
    }
}
Hi guys, I am expecting that validate function is going to be excecuted in N numbers(N = size of someList) of coroutines. hewever, my application is working sequentialy, first it is validating first element, second element and so on. Should it work sequentially? Or am I doing something wrong?
p

paulex

01/28/2020, 10:36 AM
Sorry, why do you really have to
launch
for each item?
t

Timur Atakishiev

01/28/2020, 10:39 AM
since it is long running process, I decide to use coroutines, if result is going to be as I want, size of collection = number of calling validate function, I want to show my team that we can start to use coroutines in our project
p

paulex

01/28/2020, 10:59 AM
Hi, @Timur Atakishiev I'm new to coroutines but i don't think it's going to run sequentially... I've written a small code to simulate this..
Copy code
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

suspend fun addAfterValidate(n:Int){
    delay(3000L)
    println("validating $n\n")
}

arrayListOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10).forEach { 
    GlobalScope.launch { 
        addAfterValidate(it)
    }
}
This is the response...
t

Timur Atakishiev

01/28/2020, 11:03 AM
But at my case it is working sequentially, I don`t know why.
validate
function is making some long running process. In My case there are 5 parallel calls of
validate
and then it is waits till one of that 5 parallel calls is going to be end
p

paulex

01/28/2020, 11:04 AM
perhaps validate function is a blocking call
t

Timur Atakishiev

01/28/2020, 11:09 AM
validate
is using RestTemplate, and makes some get request certain URI, is it blocking scope?
Copy code
coroutineScope {
    someList.forEach {
        launch(Executors.newSingleThreadExecutor().asCoroutineDispatcher()) {
            if (validator.validate(it)) {
                <http://log.info|log.info>("validator called on $it")
                someStorage.add(it)
            }
        }
    }
}
Found a solution for my problem, who knows whether it is okay or not?
👍 1
4 Views