I want to implement a suspending function that starts a coroutine which runs a background job in a loop.
Imagine a connect()
function which, once the connection is establishes, needs to spawn a coroutine that receives data in the background continuously, in an infinite loop, until it is canceled. Here’s some pseudo code:
suspend fun connect() {
// connection is established here
backgroundJob = launchInTheBackground { // This is the unclear part
while (true) {
val myData = receiveData(); // This is a suspend function
processReceivedData(myData);
}
}
}
suspend fun disconnect() {
backgroundJob.cancel()
backgroundJob = null
// disconnecting is done here
}
The launchInTheBackground
part is what is unclear to me. What I want to do is to start a coroutine in the same scope that connect()
is called in. This is important to make sure that connect()
does not wait until the loop finishes (which it never does except when you cancel the coroutine).
So far, I had to pass the coroutine scope explicitely. Then I can replace launchInTheBackground
with scope.launch
. But having to explicitely pass a scope to the function is not exactly nice. I wonder if you guys can think of a better approach here?