Kotlin suspend 回调使用

本文探讨了在Kotlin中如何使用协程处理回调,详细解释了如何通过协程来避免回调地狱,包括如何启动job协程以及GlobalScope的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

kotlin 回调使用方式

某些业务上协程的使用导致需要回调方式获取结果
回调接口和引用回调的方法:

/**
 * 回调接口
 */
public interface CallbackListener<T>{
    /**
     * 回调方法
     * @param msg 回调消息
     */
    void invoke(Result<T> msg);
}
/**
 * 回调方法
 */
suspend fun sendSnsFromOss(loginUser: String, uin: Long, param: SendSnsParam, listener: CallbackListener<WsMessage<Any>>)

/**
 * 回调方法实现
 */
override suspend fun sendSnsFromOss(loginUser: String, uin: Long, param: SendSnsParam, listener: CallbackListener<WsMessage<Any>>) = coroutineScope {
	//业务内容
	val result: Result<WsMessage<Any>> = Result()
	var xml: String? = null
	xml = suspendCoroutine<String> {
                launch {
                    snsUploadImageFromOss(loginUser, uin, param) { result ->
                        it.resume(result!!)
                    }
                }
            }
	...
	listener.invoke(result)
}

使用协程



/**
 * 调用回调方法
 * job:协程标识,控制生命周期
 */
override suspend fun pushSns(taskParam: TaskParam, job: Job) {
		//作用域
        val scope = CoroutineScope(job)
        scope.launch(ContextAware.IO) {
        	//检测当前是否在线(job检测是否取消,其他业务中执行中离线会调用job.cancel使job取消)
       		if (job.isCancelled) {
       			...
        		throw BusinessException(ResultCode.TASK_WECHAT_APPLY_OFFLINE, ResultCode.TASK_WECHAT_APPLY_OFFLINE.desc);
            }
            //回调使用
        	val result = suspendCoroutine<Result<WsMessage<Any>>> {
                        launch {
                            snsService!!.sendSnsFromOss(taskParam.ownerUser, taskParam.uin, param) { result -> 														
                            it.resume(result)
                            }
                        }
             }
             if (result.code == ResultCode.RESULT_SUCCESS.type) {
             			...
             } else {
             	...
             }
		     //回调使用添加超时
             val result = withTimeoutOrNull(5 * 60 * 1000L) {
                     suspendCoroutine<Result<WsMessage<Any>>> {
                         launch {
                             userInfoService!!.sendSnsFromOss(taskParam.ownerUser, taskParam.uin, param) { result ->
                                     it.resume(result)
                             }
                         }
                     }
             }
             if (result.code == ResultCode.RESULT_SUCCESS.type) {
             			...
             } else {
             	delay(1000)
             	...
             }  
                    
        }

关于上面的job协程

也可以使用GlobalScope开启全局域启动


    @Deprecated("")
    override suspend fun pushSnsTask(taskParams: List<TaskParam>) {
        GlobalScope.launch(ContextAware.IO) {
	        val result = suspendCoroutine<Result<WsMessage<Any>>> {
	                                launch {
	                                    snsService!!.sendSnsFromOss(taskParam.ownerUser, taskParam.uin, param) { result ->
	                                        if (result.code == ResultCode.RESULT_SUCCESS.type) {
	                                            it.resume(result)
	                                        }
	                                    }
	                                }
	         }
	         ...           
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值