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

nitrog42

09/24/2019, 8:18 AM
Hello, quick question about suspend and cancellation, what would be the best way to cancel early a suspend method that iterate on a list (using map operator) ?
Copy code
suspend fun mappingFunction(dataToMap: List<String>) {
        val mappedData = dataToMap.map { 
            
        }
        
        // run suspendable work with mappedData
    }
g

gildor

09/24/2019, 8:20 AM
return@mappingFunction
n

nitrog42

09/24/2019, 8:23 AM
I’m sorry I meant, if the coroutine is cancelled, the map will still run until we go to the suspendable work here, which will check if the coroutine is active and then cancel itself right ? So is there anyway to make the map cancel itself ?
using a sequence or a flow maybe ?
g

gildor

09/24/2019, 8:31 AM
actually you can just use
return
, no need to use label in this case
Ahhh, I got what you mean. Depends on what is inside of your
map
if you call any other suspend function it will be cancelled, if you do not call any suspend functions, so don’t have any cancellation points, you can call
yield()
which creates empty suspend (and cancellation) point
But if this map is very fast, I actually think that would be faster just allow it finish work and cancel later than check on every iteration
n

nitrog42

09/24/2019, 8:55 AM
i have 4 sequentials map actually (4 lists), but calling yield between is a good idea
g

gildor

09/24/2019, 9:00 AM
4 maps in one chain?
n

nitrog42

10/14/2019, 8:14 AM
20 days later => no, I have 4 differents lists (of different objects) and needed to do operation on each, which can take time
3 Views