协程科特林无法正常工作

时间:2019-04-06 08:50:39

标签: android kotlin coroutine

我正在使用kotlin协程,有2个问题-

1)我的API调用发生在我实际上想要在Main thread上的IO上,而UI回调发生在了Main thread上。

2)job.cancel()似乎无效。当API调用正在进行并且我想停止它时,我调用stopAPICall(),但似乎没有效果

class MyDetails(val callback: Callback,
                                   private val coroutineCtx: CoroutineContext = Dispatchers.Main) : KoinComponent, CoroutineScope {

    private val job = Job()
    private val repo: IRepo by inject { parametersOf(this) }

    override val coroutineContext: CoroutineContext
        get() = job + coroutineCtx

    fun verifyMyDetails(id: String?) = launch {
        Log.e("TAG","Coroutines started =" + Thread.currentThread().name)  //Prints Main
        val response = repo.processId(id)

        when (response) {
            is APIResult.Success -> {
                Log.e("TAG","Updating UI =" + Thread.currentThread().name) //Prints Main
                callback.onSuccess(response.data.myDetails)
            }
            is APIResult.Error -> {
                callback.onAPIError(response.code)
            }
        }
    }

    fun stopAPICall() {
       job.cancel()
    }
}

class Repo(): IRepo {
    override suspend fun processId(id: String) {
       val response = apiInterface.processIdCall(id).await()
       try {
          return ...
       } catch(e: HttpException) {
          return ...
       }
    }
}

0 个答案:

没有答案