https://kotlinlang.org logo
#android
Title
# android
r

reactormonk

04/02/2024, 9:34 AM
Where do I put the
withContext(<http://Dispatchers.IO|Dispatchers.IO>) { }
? ViewModel?
s

SanjayKarki

04/02/2024, 9:41 AM
may be with viewmodelscope
r

Robert Williams

04/02/2024, 10:20 AM
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

Michael Krussel

04/02/2024, 1:34 PM
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

reactormonk

04/03/2024, 5:05 PM
Aka push it down as far as possible?
👌 1
m

Mofe Ejegi

04/04/2024, 11:05 PM
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

Robert Williams

04/05/2024, 10:03 AM
^ 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)
3 Views