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

Davide Giuseppe Farella

01/15/2020, 8:40 PM
Hello, can somebody explain me this? 🤨 ( Don’t mind about the typo 😄 )
d

Dico

01/15/2020, 8:45 PM
Assuming
isActive
is from
kotlinx.coroutines
, it is because there is no
Job
element in your coroutine context.
If that's not it, I have no clue what I'm looking at and you need to provide better context
d

Davide Giuseppe Farella

01/15/2020, 8:47 PM
What do you mean by
there is no
Job
element in your coroutine context
? Putting a breakpoint outside of the
object
, below
isEmpty
it is true
d

Dico

01/15/2020, 8:48 PM
There's not enough context to answer your question.
d

Davide Giuseppe Farella

01/15/2020, 9:01 PM
message has been deleted
d

Dominaezzz

01/15/2020, 9:17 PM
Yes, the
coroutineScope
is finished when
iterator
returns, so it prints false.
☝️ 1
s

streetsofboston

01/15/2020, 9:18 PM
If you move the
coroutineScope
from the
AnIterableClass#iterator()
function and add it to the
hasNext()
function instead, you get what you expect
d

Davide Giuseppe Farella

01/15/2020, 9:33 PM
Thank you guys, so which would be the correct way? 🤔
d

Dominaezzz

01/15/2020, 9:35 PM
Depends on what you're trying to achieve but as a guess, I'd say you don't need the
coroutineScope
for the iterator at all, you can just do
coroutineContext.isActive
I think.
Or use
Flow
....
s

streetsofboston

01/15/2020, 9:37 PM
If you really need to use your own iterable and the isActive:
Copy code
class AnIterableClass {
    operator fun iterator() = 
        object : SuspendIterable {
        	override suspend fun hasNext(): Boolean = coroutineScope {
                println("2 $isActive")
                false
        	}
    	}
    
}
The
couroutineScope
closure is moved to the
hasNext
. (and
suspend
has been removed from
iterator
).
👍 1
3 Views