Dispatchers.IO running on main thread? - android

Consider the following code:
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
lifecycleScope.launchWhenCreated {
with(Dispatchers.IO) {
if (Looper.myLooper() == Looper.getMainLooper()) {
throw Exception("we are on the main thread, though Dispatchers.IO is used")
}
}
}
}
}
Actually that does throw the exception
java.lang.Exception: we are on the main thread, though Dispatchers.IO is used
but why? Shouldn't Dispatchers.IO use a background thread?
(Hint: I am aware that in most cases I better use the ViewModel scope for coroutines, but that's not the question here - I want to understand why the current code throws the exception)

You've mistaken scope function with coroutine one:
with(Dispatchers.IO){ } - a blocking call where lambdas body is scoped (this === Dispatchers.IO)
withContext(Dispatchers.IO){ } - suspending call executed in provided context (in this case it switches dispatcher) that returns a result to original context

Related

How to start a coroutine on main thread without using GlobalScope?

Whenever I want to start a coroutine on a main thread,
fun main(args: Array<String>) {
GlobalScope.launch {
suspededFunction()
}
}
suspend fun suspededFunction() {
delay(5000L) //heavy operation
}
GlobalScope is highlighted, and always taunt that its usage is delicate and require care.
What delicacies are involved with GlobalScope, and importantly how can I start a coroutine without using GlobalScope?
To start coroutine without using a GlobalScope, one can do as:
val job = Job()
val scope = CoroutineScope(job)
scope.launch {
suspededFunction()
}
As mentioned in comments, some classes already have scopes available, like ViewModel class as viewModelScope.
in Activity or Fragment you can as follows:
//not recommended to use co-routines inside fragment or activity class
// this is just for example sack shown here.
// otherwise you have to do all your processing inside viewmodel
class Fragment : CoroutineScope by MainScope() {
...
override fun onDestroy() {
super.onDestroy()
cancel()
}
}
Kotlin already created some scope. you can use it according to your situation. and you also create your own scope. but I suggest in the beginning it is better to use that already created
check official documentation https://developer.android.com/topic/libraries/architecture/coroutines
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewBinding = ActivityMainBinding.inflate(layoutInflater)
setContentView(viewBinding.root)
lifecycleScope.launch {
//for activity
}
}
//for viewmodel
suspend fun abc() = viewModelScope.launch {
}

How to return callback/stream to the caller thread?

I have some class 'A', the internal work of which is performed using rx or coroutines with flows. Class 'A' should not return any instances of rx/coroutines (and flows), their work should be hidden, we need Future result for callbacks and observe on custom Observer.
Caller class 'B' can call A's methods on the main(UI) thread or another thread. If the methods are called on Ui thread, it's easy because we can observe on Main thread and use corresponding coroutine scope.
But how do we deal with this situation if the caller's thread is not main?
Use Handler
class A {
private val mainHandler = Handler(Looper.getMainLooper())
fun <T> observe(onChanged: (T) -> Unit) {
...
mainHandler.post { onChanged(value) }
}
}
How do your classes A and B look like?
But how do we deal with this situation if the caller's thread is not
main?
If your code in B is ran in a coroutine, then use withContext() and just make the call on the main thread:
class B(private val a: A) {
fun doStuffIn(scope: CoroutineScope) {
scope.launch {
...
withContext(Dispatchers.Main) {
a.collectData()
}
}
}
// or:
fun CoroutineScope.doStuff() {
launch {
...
withContext(Dispatchers.Main) {
a.collectData()
}
}
}
// or:
suspend fun doStuff2() {
...
withContext(Dispatchers.Main) {
a.collectData()
}
}
}

How to Inject Other Dispatchers to MainCoroutineRule?

In the Google Codelab for Coroutines, we are shown a MainCoroutineScopeRule. Within the rule, it explains that this rule can be extended to other dispatchers in addition to Dispatchers.Main:
override fun starting(description: Description?) {
super.starting(description)
// If your codebase allows the injection of other dispatchers like
// Dispatchers.Default and Dispatchers.IO, consider injecting all of them here
// and renaming this class to `CoroutineScopeRule`
//
// All injected dispatchers in a test should point to a single instance of
// TestCoroutineDispatcher.
Dispatchers.setMain(dispatcher)
}
My question is, how exactly are we to inject the other dispatchers? Does this assume that we're using dependency injection? If so, what if I'm not using DI, can I still extend this rule to the other dispatchers? I don't see anything in the kotlinx-coroutines-test library that allows me to set the TestCoroutineDispatcher to the other dispatchers. So, there's this:
Dispatchers.setMain(dispatcher)
...but not this:
Dispatchers.setIO(dispatcher) // Or Default, etc.
Am I instead expected to rewrite my suspend functions to take in a dispatcher as a parameter:
suspend doSomeIO(dispatcher: CoroutineDispatcher = Dispatchers.IO) {
launch(dispatcher) {
// Some long-running IO operation
}
}
You are correct in that this does assume you are injecting your dispatchers. If you are not using the main dispatcher, you should be injecting the dispatcher in order to test it properly.
The way you wrote the suspend function is one way to do it, if you want to force that particular function to be on the Dispatchers.IO thread. However, then you will end up having nested launches.
Instead of that, I would just pass the dispatcher in to a viewModel, and let the viewmodel decide how to call the suspend function.
//Your version:
suspend fun doSomeIO(dispatcher: CoroutineDispatcher = Dispatchers.IO) {
launch(dispatcher) {
// Some long-running IO operation
}
}
class MyViewModel(val dispatcher: CoroutineDispatcher = Dispatchers.IO: ViewModel() {
init {
viewModelScope.launch {
doSomeIO(dispatcher) // here you are launching one coroutine inside the other
}
}
}
// Instead try this:
suspend fun doSomeIO() {
// Some long-running IO operation
}
class MyViewModel(val dispatcher: CoroutineDispatcher = Dispatchers.IO: ViewModel() {
init {
viewModelScope.launch(dispatcher) {
doSomeIO()
}
}
}

What is the lifetime of coroutineScope in Kotlin?

The Code A is from the project architecture samples at https://github.com/android/architecture-samples
1: I don't know if the function activateTask(task: Task) need to be wrapped with runBlocking just like Code B. I'm afraid that activateTask(task: Task) maybe not be run if the object of DefaultTasksRepository is destroyed quickly.
2: Normally I run coroutines in ViewModel.viewModelScope, I don't know whether the ViewModel.viewModelScope will be destroyed when I finish the app, and whether the coroutines running in ViewModel.viewModelScope will be destroyed too. If so, I think it will be bad, some long time coroutines such as writing data to remote server will be cancel.
3: And more, the function activateTask in Code A is a coroutines function, it can invoke another coroutines function directly, so I think the Code A+ is correct, right?
Code A
import kotlinx.coroutines.coroutineScope
...
class DefaultTasksRepository(
private val tasksRemoteDataSource: TasksDataSource,
private val tasksLocalDataSource: TasksDataSource,
private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO
) : TasksRepository {
...
override suspend fun activateTask(task: Task) = withContext<Unit>(ioDispatcher) {
coroutineScope {
launch { tasksRemoteDataSource.activateTask(task) }
launch { tasksLocalDataSource.activateTask(task) }
}
}
override suspend fun clearCompletedTasks() {
coroutineScope {
launch { tasksRemoteDataSource.clearCompletedTasks() }
launch { tasksLocalDataSource.clearCompletedTasks() }
}
}
...
}
Code A+
import kotlinx.coroutines.coroutineScope
...
class DefaultTasksRepository(
private val tasksRemoteDataSource: TasksDataSource,
private val tasksLocalDataSource: TasksDataSource,
private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO
) : TasksRepository {
...
override suspend fun activateTask(task: Task) = withContext<Unit>(ioDispatcher) {
tasksRemoteDataSource.activateTask(task)
tasksLocalDataSource.activateTask(task)
}
override suspend fun clearCompletedTasks() {
tasksRemoteDataSource.clearCompletedTasks()
tasksLocalDataSource.clearCompletedTasks()
}
...
}
Code B
fun main() = runBlocking {
launch {
delay(1000L)
println("World!")
}
println("Hello,")
}
You should not use runBlocking in any coroutine application, it blocks the thread.
If you really want to make activateTask non-cancellable there is a factory implementation of NonCancellable already in the stdlib
And you should not use coroutineScope wrapper inside the withContext, as a newly created CoroutineScope along with a new job is already passed as receiver within withContext.
Implement your activateTask like this:
override suspend fun activateTask(task: Task) = withContext<Unit>(ioDispatcher + NonCancellable) {
launch { tasksRemoteDataSource.activateTask(task) }
launch { tasksLocalDataSource.activateTask(task) }
}
In this way it will be called on the IODispatcher but will not be cancellable since the Job element of the resulting context does not provide functionality to cancel it.
ViewModelScope runs till your application is destroyed, more info and lifecycle chart is here. If you want to run some very important tasks, then use other dispatchers.
Yes code A+ is completely correct
PS: You should not implement runBlocking in a coroutine application, its default implementation is just the event loop.
runBlocking is the way to bridge synchronous and asynchronous code
Better implementation of main function should be:
suspend fun main() = coroutineScope {
// code here
}
It runs on the CommonPool, and if it suspends another coroutine could reuse the same thread.

Testing coroutines in the presenter class

I'm struggling to test my presenter which is calling a suspended function from the repository layer as follow:
override fun viewCreated() {
launch {
val hasPermission = permissionChecker.execute() //suspended function
if (hasPermission) {
foo()
} else {
view.bar()
}
}
The presenter is also extending this interface:
interface CoroutinePresenter: CoroutineScope {
val job: Job
override val coroutineContext: CoroutineContext
get() = Dispatchers.Main + job
fun stopAllActiveJobs() {
coroutineContext.cancelChildren()
}
And the suspended function is defined as follow:
suspend fun execute() : Boolean = withContext(Dispatchers.IO) {
return#withContext class.foo()
}
Everything is working as expected in the app but when I tried to write some unit test I noticed that whenever I call the piece of code inside launch the thread is switched but the test doesn't wait for the execution. This is the implementation of the test:
#Test
fun `Test of Suspended Function`() = runBlocking {
presenter.viewCreated()
then(view).should().bar()
...
}
I also added the suggested library for testing kotlinx-coroutines-test but the result is still the same with it. I also tried to follow this suggestion and also implementing something like this but still no luck.
I think the problem is the actual creation of another thread whenever the launch is invoked in the presenter and the test doesn't actually know how to wait for it. I also tried to return a Job and invoking the job.join() but it fails with a NullPointerException.
Hope you guys can help me.
I found a solution for that:
following this tutorial, I've setup both
#Before
fun setup() {
Dispatchers.setMain(Dispatchers.Unconfined)
...
}
#After
fun tearDown() {
Dispatchers.resetMain() // reset main dispatcher to the original Main dispatcher
}
And by running the entire launch block of the presenter class inside a runBlocking statement in the test. The problem was related also to a not reported exception inside the suspended function that was actually not mocked but it was invisible to my eyes.
Now everything is working fine.
Firstly, I strongly recommend that give your coroutineContext as a Parameter like that:
class CoroutinePresenter(coroutineContext: CoroutineContext): CoroutineScope {
init{
_coroutineContext = coroutineContext
}
override val coroutineContext: CoroutineContext
get() = _coroutineContext
// Your Methods
}
In your real environment:
#YourScope
#Provides
fun providesCoroutinePresenter(coroutineContext:CoroutineContext ){
return CoroutinePresenter()
}
#YourScope
#Provides
fun providesCoroutineContext(){
return Dispatchers.Main + job
}
During the unit test:
#Before
fun setUp() {
coroutinePresenter CoroutinePresenter(Dispatchers.Unconfined)
}
#Test
fun `Should do something`(){
//WHEN
coroutinePresenter.doSomething(params)
//THEN
do your assertions
}
For more please check SOLID Principles and for this case D

Categories

Resources