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

chirag

02/16/2018, 7:57 AM
Hey all ,Just need an advice here using Coroutines in kotlin : Should we call async methods in properties of class, and await in class methods whenever they would be called For Ex -
Copy code
class DataAccess(val id:String) {
    
    private val fooAsync = async { fetchDataFromTableA(id) }
    private val barAsync = async { fetchDataFromTableB(id) }

    fun getData(): Data {
        var foo =fooAsync.await()
        var bar = barAsync.await()
        
        return compute(foo,bar)
    }
}
Just want to know ,Is it right way to do it ?
j

Jonathan

02/16/2018, 8:09 AM
I think yes. If your goal is to eagerly trigger the data fetch and cache the result. (note that 'getData' should be 'suspend')
Note that the fetch could be lazy with the folowing:
Copy code
class DataAccess(val id:String) {

  private val fooAsync = async(start = CoroutineStart.LAZY){ fetchDataFromTableA(id) }
  private val barAsync = async(start = CoroutineStart.LAZY){ fetchDataFromTableB(id) }

  suspend fun getData() {
    barAsync.start()

    val foo = fooAsync.await()
    val bar = barAsync.await()

    return compute(foo,bar)
  }
}
Note: I would personally never call a suspending function getXxx(). I would prefer fetchXxx() or findXxx() or whatever. Just because (in my opinion) a getter should normally not be suspending. But that's just naming convention and I don't even know if is shared by others.
c

chirag

02/16/2018, 8:46 AM
@Jonathan Thanks for reply, how the Lazy would benefit than normal async Couroutine ,or why should i do this?
@Jonathan point noted , no this has not been shared yet ,Its just example i made to illustrate example . I would take care this convention while coding
j

Jonathan

02/16/2018, 8:57 AM
For the lazy, it depends on your need. If you don't use it, creating an instance of
DataAccess
would trigger the data fetch. If you use it, the data fetch would be triggered at the first call of
getData
which could be later.
c

chirag

02/16/2018, 9:05 AM
Okay but if i have some other function in which i want to start that coroutine if some condition satisfies.
Then how can i trigger it
j

Jonathan

02/16/2018, 9:08 AM
you can start the fetch with
fooAsync.start()
c

chirag

02/16/2018, 7:08 PM
@Jonathan thanks i learnt something new, i tried lazy coroutine, its working as expected :)
2 Views