2 years ago

#51106

test-img

strok_777

Test job cancellation on Android with Coroutines

I'm working on a RN library where MyClassis some kind of View and I inject a coroutineScope in order to be able to test it. The code looks similar to the following one:

class MyClass(scope:CoroutineScope){
  
  private lateinit var myJob : Job?
  
  fun myMethod() {
    myJob = scope.launch {
      val someObject = getSomeObject()
      if (someObject != null && isActive) {
        doSomething()
      }
    }
  }
  
  fun onDestroy(){
    cancelJob()
  }

  private fun cancelJob() {
    if (myJob != null && myJob!!.isActive) {
      myJob!!.cancel()
      myJob = null
    }
  }
}

And I have two questions about it. First I'd like to write a unit to verify that when the coroutineScope is cancelled, then the job.cancel is called.

And my second question is: is it a best practice to keep a reference of the job inside a a class? wouldn't that produce a memory leak? But I want to keep track of the job to cancel it and not execute doSomething() when the coroutine scope is cancelled.

android

unit-testing

kotlin

kotlin-coroutines

android-testing

0 Answers

Your Answer

Accepted video resources