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

elizarov

01/29/2019, 7:19 AM
It depends on what you want
doSomething
to do: • If you want to wait until it finishes doing its work you write
suspend fun doSomething() = coroutineScope { ... }
• If you want it to return quickly with a side effect of launching new coroutine, you write
fun CoroutineScope.doSometing() = launch { ... }
.
s

svenjacobs

01/29/2019, 7:35 AM
But extensions functions are static, right? So this would not work
Copy code
class EventBus {
  fun CoroutineScope.send(...) { ... }
}

// somewhere else
val eventBus = EventBus()
launch {
  eventBus.send(...)
}
At the moment I have
Copy code
class EventBus {
  fun send(scope: CoroutineScope, ...) { ... }
}
r

Ruckus

01/29/2019, 7:37 AM
No, they are not static, they are resolved statically. It's an important distinction.
s

svenjacobs

01/29/2019, 7:38 AM
So is there a way I can get the first version of
EventBus
to work?
r

Ruckus

01/29/2019, 7:39 AM
Sure, if "somewhere else" is in a CoroutineScope, you can just use
Copy code
val eventBus = EventBus()
with(eventBus) {
    send()
}
Sorry, I fixed my copy/paste error
s

svenjacobs

01/29/2019, 7:42 AM
Okay, the solution with
with()
works but not without. Why is that?
r

Ruckus

01/29/2019, 7:43 AM
Because you need to be in the context of
EventBus
to use extension methods declared in it. It's a scoping issue, not specific to coroutines.
s

svenjacobs

01/29/2019, 7:45 AM
Okay, but still is a bit confusing because when I type
eventBus.
I thought everything after the
.
is then called in the context of
EventBus
. So I'm calling the function on the object. I wonder if this should work for extension function of the object, too?
So when I'm in the context of a
CoroutineScope
, why shouldn't the compiler be able to do this
Copy code
eventBus.send(...)
and pass the
CoroutineScope
as the first function argument during compile time.
r

Ruckus

01/29/2019, 7:56 AM
No,
eventBus.foo()
calls
foo
on
eventBus
not in the context of
eventBus
"In the context of" basically means
this
points to the thing. so in
Copy code
with (eventBus) {
    send()
}
You're calling
send()
on the CoroutineScope, but the call is being made in the context of
eventBus
.
s

streetsofboston

01/29/2019, 12:21 PM
@svenjacobs This "In the context" of works, because methods (functions) in Kotlin can have two receivers, like the
inContext
function below.
Copy code
class MyClass {
    fun printValue(value :Int) {
        println("Value ${value.inContext()}")
    }

    fun Int.inContext(): String {
        return (this + 6).toString() + this@MyClass.hashCode().toString()
    }
}

fun main() {
    MyClass().printValue(4)
}
r

Ruckus

01/29/2019, 2:30 PM
@streetsofboston Thanks, I don't think I was explaining that well at all 🙂
2 Views