3

I have lifecycle aware coroutine

abstract class AppViewModel : ViewModel(), CoroutineScope {

    private val job = Job()
    override val coroutineContext: CoroutineContext
        get() = Dispatchers.Main + job

    override fun onCleared() {
        super.onCleared()
        job.cancel()
    }
}

if i use in my viewmodel

launch {

}

it causes disk violation

D/StrictMode: StrictMode policy violation; ~duration=200 ms: android.os.strictmode.DiskReadViolation

on this line

get() = Dispatchers.Main + job

what I'm doing wrong?

EDIT

I have created another example, and this error still exists

class MainActivity : AppCompatActivity(), CoroutineScope {

    protected val job = SupervisorJob()
    override val coroutineContext = Dispatchers.Main + job

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        launch {
            val e = withContext(Dispatchers.Default) {
                4
            }

            text.text = e.toString()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        job.cancel()
    }
}

1 Answers1

0

This error occurs when you try to execute queries in the UI thread. According to your code try to change coroutine context in that way:

//Code here stays same
override val coroutineContext: CoroutineContext
  get() = Dispatchers.IO + job
//Code here stays same

So here you will launch your coroutines on the IO-threads and off the UI-thread.

Hopefully it'll help!

aLT
  • 326
  • 3
  • 9