Is there a good way to swap/share scopes in corout...
# coroutines
m
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
from what I read at https://stackoverflow.com/a/48460886/436524, it sounds like you actually want more of a BroadcastChannel
m
But BroadcastChannel only broadcasts the data
I want to manage the scope
o
I'm not sure what you mean by "scope"?
coroutineScope
?
m
CoroutineScope
yes
sorry for confusion
m
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
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
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
@Matej Drobnič I've asked about your use case in the issue, I hope you don't mind
m
No biggie, I'm actually participating in that issue (first comment is mine 😄 )