|
|
@@ -7,14 +7,55 @@ import kotlinx.coroutines.Job
|
|
|
|
|
|
//open class BasePresenterKt : AndroidViewModel(Utils.getApp()) {
|
|
|
abstract class BasePresenterKt<V : IView>: BasePresenter<V>() {
|
|
|
+ private val mProgressJobList = ArrayList<Job>()
|
|
|
+ private val mBackgroundJobList = ArrayList<Job>()
|
|
|
+
|
|
|
/**
|
|
|
* 所有网络请求都在 rxLifeScope 域中启动,当页面销毁时会自动
|
|
|
* 取消所有协程
|
|
|
* @param block 网络请求
|
|
|
* @param onError 失败回调
|
|
|
- *
|
|
|
+ * 可见任务
|
|
|
+ */
|
|
|
+ fun launchProgressTask(block: suspend CoroutineScope.() -> Unit, onError: ((Throwable) -> Unit)? = null): Job {
|
|
|
+ var job : Job? = null
|
|
|
+ job = rxLifeScope.launch(block, onError, {}, { mProgressJobList.remove(job) })
|
|
|
+ mProgressJobList.add(job)
|
|
|
+ return job
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 不可见任务
|
|
|
+ */
|
|
|
+ fun launchBackgroundTask(block: suspend CoroutineScope.() -> Unit, onError: ((Throwable) -> Unit)? = null): Job {
|
|
|
+ var job : Job? = null
|
|
|
+ job = rxLifeScope.launch(block, onError, {}, { mBackgroundJobList.remove(job) })
|
|
|
+ mBackgroundJobList.add(job)
|
|
|
+ return job
|
|
|
+ }
|
|
|
+
|
|
|
+ override fun onProgressTaskCancel() {
|
|
|
+ super.onProgressTaskCancel()
|
|
|
+ recycleTask(mProgressJobList)
|
|
|
+ }
|
|
|
+
|
|
|
+ override fun onBackTaskCancel() {
|
|
|
+ super.onBackTaskCancel()
|
|
|
+ recycleTask(mBackgroundJobList)
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 取消任务
|
|
|
*/
|
|
|
- fun launchTask(block: suspend CoroutineScope.() -> Unit, onError: ((Throwable) -> Unit)? = null): Job {
|
|
|
- return rxLifeScope.launch(block, onError)
|
|
|
+ private fun recycleTask(jobList : ArrayList<Job>) {
|
|
|
+ val size = jobList.size
|
|
|
+ var index = 0
|
|
|
+ while (index < size) {
|
|
|
+ if (jobList[index].isActive) {
|
|
|
+ jobList[index].cancel()
|
|
|
+ }
|
|
|
+ jobList.removeAt(index)
|
|
|
+ index++
|
|
|
+ }
|
|
|
}
|
|
|
}
|