首页 > 解决方案 > WorkManager 做一个异步工作

问题描述

我有一个 Android 聊天应用程序,由于我在业务模型中存在一些连接问题,我希望有一个执行以下操作的定期任务。

class PendingMessagesWorker(
    appContext: Context,
    params: WorkerParameters
) : CoroutineWorker(appContext, params), KoinComponent {

    override suspend fun doWork(): Result = coroutineScope {
        
        // 1. connect to a Socket synchronously

        // 2. if connected then send a socket message that requests 
        // from server to response with pending messages

        // 3. IF and WHEN server responds, handle the new messages


        Result.success()
    }

}

问题是,在步骤 2 - 3 之间,我应该在请求中添加回调还是添加延迟(x 秒)以使工作人员“等待”结果?

如果我在请求中添加回调,工人不是要完成并销毁所有线程吗?

标签: androidkotlinwebsocketandroid-workmanager

解决方案


推荐阅读