Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

popupwindow或者dialog里面的网络请求也要回调到UI层进行处理吗,感觉有点麻烦,能否直接在弹框里面请求网络呢 #115

Open
geziin opened this issue Aug 4, 2022 · 3 comments

Comments

@geziin
Copy link

geziin commented Aug 4, 2022

No description provided.

@liangjingkanji
Copy link

建议试试协程网络请求同步写法例如Net, 没有回调

// 自动显示/关闭对话框
scopeDialog {
    val result = Get<Data>("/api").await()
}

// 页面关闭自动取消
scopeNetLife {
    val result = Post<Data>("/api").await()
}

@ruirui1128
Copy link

ruirui1128 commented Sep 16, 2022

也可以自定义协程的扩展
在Dialog使用MainScope()

fun <T> CoroutineScope.http(
    request: suspend () -> BaseResponse<T>,
    response: (T) -> Unit,
    error: (Throwable) -> Unit = {}
): Job {
    return launch {
        kotlin.runCatching {
            request()
        }.onSuccess {
            response(it.getResponseData())
        }.onFailure {
            error(it)
        }
    }
}
class MyDialog(context: Context) : Dialog(context) {

    ........

    var exampleJob: Job? = null
  
    fun httpExample() {
        exampleJob?.cancel()
        exampleJob =  MainScope()?.http(
            request = { apiService.getUserInfo() },
            response = { }
        )
    }

  
 override fun cancel() {
        super.cancel()
       exampleJob?.cancel()
    }

}

@ruirui1128
Copy link

扩展一点来讲,api接口是suspend关键字修饰的,只要可以开启协程都可以进行网络请求
如在自定义线程中,执行网络任务

class TaskTask1() : Runnable {
    override fun run() {
    val data = runBlocking {             //阻塞当前线程
            try {
                ApiClient.appApi.getBanner()
            } catch (e: Exception) {
                null
            }
        }
        //线程继续执行
        if (data?.isSucces()==true) {
        }

    }
}

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants