Hi guys and a big thanks in advance: I want to so...
# coroutines
d
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
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
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
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
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
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
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