zjuhasz
09/16/2018, 11:55 AMCoroutineScope, unless the coroutines created by that class should always act globally for the full lifetime of the application. This means every class that launches coroutines should be created through an extension function on CoroutineScope like CoroutineScope.MyClass(). So MyClass needs a constructor that takes scope as a parameter, then we need to make an extension function for CoroutineScope that is an exact copy of the constructor for MyClass except it uses this from CoroutineScope instead of taking scope as a parameter. If there is a class with several constructors that each have several parameters this can be really annoying and a bit hard to maintain. Is there a better way for me to be scoping the coroutines launched by classes?zjuhasz
09/16/2018, 12:07 PMclass MyClass(scope: CoroutineScope): CoroutineScope {
private val job: Job = Job(scope.coroutineContext[Job])
override val coroutineContext: CoroutineContext = scope.coroutineContext + job
init {
doStuffWhileIExist()
}
private fun doStuffWhileIExist() {
launch {
while (isActive) {
println("I am doing stuff!")
delay(100)
}
}
}
fun cancel() = job.cancel()
}
fun CoroutineScope.MyClass() = MyClass(this)pakoito
09/16/2018, 1:28 PMpakoito
09/16/2018, 1:29 PMzjuhasz
09/16/2018, 2:32 PMdave08
09/16/2018, 2:35 PMzjuhasz
09/16/2018, 2:38 PMdave08
09/16/2018, 2:54 PMzjuhasz
09/16/2018, 4:59 PMelizarov
09/17/2018, 12:55 PMViewModel classes that all implement CoroutineScope in the same way and thus CoroutineScope can be implemented by some BaseViewModel class, but I don’t see much use-cases for building the whole hierarchy of scope in a typical app.zjuhasz
09/18/2018, 11:19 AMzjuhasz
09/18/2018, 11:41 AMCoroutineScope.constructor. I guess on JVM it would just show up as a constructor that takes the receiver as a parameter. Again, not sure if it's worth it but maybe with this change to kotlinx.coroutines it's worth considering / reconsidering. If nothing else, it would be useful to have an IntelliJ shortcut for generating extension functions from constructors with one of the parameters as ther receiver.