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)
}
}
}
}
...
}
}