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

Daniel

07/12/2019, 7:07 PM
Hi guys and a big thanks in advance: I want to solve the following problem and I honestly don't know where to start googling it 😕 Lets say we have a database class and it has two methods:
Copy code
class Database {
    fun prefillDatabase() {
      // launch a non blocking job here that puts some data in the database
      // image this is done on application start
    }

    suspend fun getEntities() {
      // launch a blocking coroutine to get all entities of the database but only AFTER the job in prefillDatabase() completed
      // imagine this is called later in the application on button click.
    }
}
Is this a case for .join()? The job started in prefillDatabase() could already be well completed before getEntities() is called
👌 1
s

streetsofboston

07/12/2019, 7:11 PM
I assume the first one (prefill) is called in the app start up and ‘getEntities’ is called somewhere else completely different, but you want to make sure that ‘prefill’ has done its job before ‘getEntities’ start doing its work. Correct?
If so, then yes, in ‘getEntities’, join() on the Job created by the ‘prefill’ call
d

Daniel

07/12/2019, 7:13 PM
Fulley correct, yes! And ahhh! The execution in getEntities would suspend on .join() until its execution is complete and would do nothing if its already completed, right?
s

streetsofboston

07/12/2019, 7:13 PM
That’s the idea. The
join
function is a suspend function.
Also, this assumes that
prefill
is called only once… other wise you’ll have a bit more work to do 🙂
d

Daniel

07/12/2019, 7:15 PM
Hmm, after looking at the documentation:
Copy code
* If the [Job] of the invoking coroutine is cancelled or completed when this
     * suspending function is invoked or while it is suspended, this function
     * throws [CancellationException].
But thats ok now I know what I have to try and where to look, a big thanks!
o

octylFractal

07/12/2019, 8:27 PM
I think that documentation doesn't mean what you think it means -- it means that if the
getEntities
coroutine is cancelled/completed,
join
throws
CancellationException
-- not if
prefill
is completed.
g

gildor

07/13/2019, 2:22 AM
Join is way to do that, you should just save this job to some filed, you even can init db instance inside and cache using async{} which caches result and you can receive it using suspend function .await() It also allows to be sure that db will be prefilled only once and even make it lazy, never call prefillDatabase explicitly, but let first getEntities do this
4 Views