Where do I put the `withContext(<http://Dispatcher...
# android
r
Where do I put the
withContext(<http://Dispatchers.IO|Dispatchers.IO>) { }
? ViewModel?
s
may be with viewmodelscope
r
Depends a bit what your ViewModel is doing but usually you only want this at the lowest level where everything inside the block is synchronous/ blocking code
👆 3
You don't want to be using this when calling suspend funs or callback-based methods which should be safe to call from any thread
👆 3
m
Google promotes concept that suspend functions should all be safe to call on the main thread. https://developer.android.com/kotlin/coroutines/coroutines-adv#:~:text=You%20should%20always%20use%20withContext,or%20running%20CPU%2Dintensive%20operations. Main concept is that the view model should feel safe calling any suspending function because if that function is blocking it will switch dispatchers. Although if you know that multiple calls you are going to make will all be using
withContext(<http://Dispatchers.IO|Dispatchers.IO>)
it can be an optimization to do it yourself also to make it switch threads only once.
r
Aka push it down as far as possible?
👌 1
m
Just to add, if you're using
<http://Dispatchers.IO|Dispatchers.IO>
for network requests, client networking libs like Ktor and Apollo Kotlin (GraphQL) already implement it by default in their libraries. I believe Room DB also does this (not 100% sure). Sources: Ktor, Apollo Kotlin
r
^ All of these cases should be covered by "suspend funs or callback-based methods"
Basically, think of withContext as converting blocking code to suspending (some people are going to hate this definition but I think it covers the most common/ useful/ important case)
Also consider
runInterruptible(dispatcher)
which does the same but works better for some Java blocking methods (people are going to hate this even more so I'm going to leave now homer disappear)