hegaojian / JetpackMvvm

:chicken::basketball:一个Jetpack结合MVVM的快速开发框架,基于MVVM模式集成谷歌官方推荐的JetPack组件库:LiveData、ViewModel、Lifecycle、Navigation组件 使用Kotlin语言,添加大量拓展函数,简化代码 加入Retrofit网络请求,协程,帮你简化各种操作,让你快速开发项目
https://github.com/hegaojian/JetpackMvvm
Apache License 2.0
3.16k stars 618 forks source link

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

Open geziin opened 2 years ago

liangjingkanji commented 2 years ago

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

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

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

也可以自定义协程的扩展 在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 commented 2 years ago

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

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

    }
}