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

Matej Drobnič

06/11/2019, 8:00 AM
Is there a good way to swap/share scopes in coroutines? What I'm looking is to create long time operation that persists through multiple scopes. For example: 1. Screen A (with Scope A) starts long operation 2. User presses a button to switch to Screen B 3. Screen B (with Scope B) also starts this long operation, but since this operation is already running, it would just somehow "add its scope" 4. Screen A is closed, so Scope A that started the operation is cancelled. But since Scope B is still using this operation, it would not stop until Scope B is also cancelled. Basically coroutine analogy to Rx's share operator. I guess Flows would fit here the most?
o

octylFractal

06/11/2019, 8:03 AM
from what I read at https://stackoverflow.com/a/48460886/436524, it sounds like you actually want more of a BroadcastChannel
m

Matej Drobnič

06/11/2019, 8:04 AM
But BroadcastChannel only broadcasts the data
I want to manage the scope
o

octylFractal

06/11/2019, 8:05 AM
I'm not sure what you mean by "scope"?
coroutineScope
?
m

Matej Drobnič

06/11/2019, 8:05 AM
CoroutineScope
yes
sorry for confusion
m

Matej Drobnič

06/11/2019, 8:09 AM
parent job is the biggest point of contention here (job is started with parent of scope A but then it would somehow need to also account for scope B job)
a

Antanas A.

06/11/2019, 8:14 AM
maybe just create new object with scope C and long computation would be run on scope C
we've had similar case and have implemented with new class which handles operation and had suspend fun compute(), like:
Copy code
var result:Deferred<Result>? = null
var mutex = Mutex()
suspend fun compute():Result {
  mutex.withLock {
       if (result != null) return result.await()
       result = async(this@ScopeC) {
           doComputations() 
       }
       result.await()
  }
}
m

Matej Drobnič

06/11/2019, 8:26 AM
but that way I loose automatic scope handling
e.g. if both screens A and screen B close down, I want to cancel the operation
v

voddan

06/11/2019, 9:13 AM
@Matej Drobnič I've asked about your use case in the issue, I hope you don't mind
m

Matej Drobnič

06/11/2019, 9:42 AM
No biggie, I'm actually participating in that issue (first comment is mine 😄 )
4 Views