gregd
08/27/2019, 8:49 PMwithContext in production code (as opposite to hello world examples)…
Where do you put withContext in your code? Is it inside suspending function body, or at the call site?
Also, if you have nested suspending functions, let’s say a typical android app with ViewModel > Repository > DataSource, where DataSource contains suspending functions - where do you put withContext?
Is there any official guidelines for this?streetsofboston
08/27/2019, 8:51 PMsuspend function, around the block of code that may be blocking (e.g. network access or something).octylFractal
08/27/2019, 8:51 PMwithContext(<http://Dispatchers.IO|Dispatchers.IO>) { readFile() }octylFractal
08/27/2019, 8:52 PMcontext parameter that is more efficientstreetsofboston
08/27/2019, 8:54 PMclass DataStoreImpl(private val context: CoroutineContext, private val service: NetworkService) : DataStore {
...
suspend override fun getData() : MyResult = withContext(context) {
val nwData = service.getData() // blocking call
val data : MyResult = ... ... nwData ...
data
}
...
}
And you’d provide <http://Dispatchers.IO|Dispatchers.IO> for the context property.Marc Knaup
08/27/2019, 8:55 PMstreetsofboston
08/27/2019, 8:56 PMgregd
08/27/2019, 8:57 PMclass DataSource {
suspend fun getFile(...) = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
suspendCoroutine {
// firebase code...
}
}
}octylFractal
08/27/2019, 8:58 PM<http://Dispatchers.IO|Dispatchers.IO> if it's callback basedstreetsofboston
08/27/2019, 8:58 PMoctylFractal
08/27/2019, 8:58 PMsuspendCoroutine is the right callstreetsofboston
08/27/2019, 8:59 PMgregd
08/27/2019, 8:59 PMstreetsofboston
08/27/2019, 9:00 PMgregd
08/27/2019, 9:00 PMgregd
08/27/2019, 9:00 PMoctylFractal
08/27/2019, 9:00 PMwithContext -- it's not necessary in this case, because it's for blocking code. if you suspend, you don't need to be in that contextstreetsofboston
08/27/2019, 9:01 PMstreetsofboston
08/27/2019, 9:02 PMContinuation provided by suspendCoroutine to resume the suspend fun getFile(...).gregd
08/27/2019, 9:02 PMstreetsofboston
08/27/2019, 9:02 PMgregd
08/27/2019, 9:03 PMgregd
08/27/2019, 9:04 PMstreetsofboston
08/27/2019, 9:06 PMwithContext as well.gregd
08/27/2019, 9:07 PMclass DataSource {
suspend fun getFile(...) = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
suspendCoroutine {
firebase.getFile(...)
.addOnSuccessListener { resume(it) }
.addOnFailureListener { resumeWithException(it) }
}
}
}gregd
08/27/2019, 9:08 PMstreetsofboston
08/27/2019, 9:08 PMfirebase doesn’t require its methods to be called on a particular thread, they can be called from any thread. You won’t need withContext.gregd
08/27/2019, 9:09 PM