java-以正确的方式使用协程

java-以正确的方式使用协程,第1张

概述我是第一次实施协程.我正在为一个简单的登录应用程序遵循MVP模式.这是我的代码流-单击的登录按钮将遵循此方向-LoginFragment->LoginPresenter->储存库->APIRepository->改造接口登录响应将遵循此方向-RetrofitInterface->APIRepository->储存库->LoginPresenter->LoginFr

我是第一次实施协程.我正在为一个简单的登录应用程序遵循MVP模式.这是我的代码流-

单击的登录按钮将遵循此方向-

LoginFragment-> LoginPresenter->储存库-> APIRepository->改造接口

登录响应将遵循此方向-

RetrofitInterface-> APIRepository->储存库-> LoginPresenter-> LoginFragment

这是代码-

RetrofitInterface.kt

@POST("login")    fun loginAPI(@Body loginRequest: LoginRequest): Deferred<LoginResponse>?

这是我的Result.kt

sealed class Result<out T : Any> {    class Success<out T : Any>(val data: T) : Result<T>()    class Error(val exception: Throwable, val message: String = exception.localizedMessage) : Result<nothing>()}

APIRepository.kt

overrIDe suspend fun loginAPICall(loginRequest: LoginRequest) : Result<LoginResponse>? {        try {            val loginResponse = APIInterface?.loginAPI(loginRequest)?.await()            return Result.Success<LoginResponse>(loginResponse!!)        } catch (e : httpException) {            return Result.Error(e)        } catch (e : Throwable) {            return Result.Error(e)        }    }

仓库

overrIDe suspend fun loginUser(loginRequest: LoginRequest): Result<LoginResponse> {        if (isInternetPresent(context)) {            val result = APIRepositoryInterface?.loginAPICall(loginRequest)            if (result is Result.Success<LoginResponse>) {                val loginData = result.data                cache?.storeData(loginData)            }            return result!!        } else {            return Result.Error(Exception())        }    }

我现在如何在演示者中启动协程?我需要在后台线程上执行此API调用,然后在UI线程上发布结果吗?

解决方法:

您需要使用本地范围在Presenter中启动协程,并注入CoroutineContext才能进行更改,例如在单元测试中:

class Presenter(private val repo: Repository,            private val uiContext: CoroutineContext = dispatchers.Main) : Coroutinescope { // creating local scope    private var job: Job = Job()    // To use dispatchers.Main (Coroutinedispatcher - runs and schedules coroutines)     // in AndroID add dependency: implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-androID:1.0.1'    overrIDe val coroutineContext: CoroutineContext        get() = uiContext + job    fun detachVIEw() {        // cancel the job when vIEw is detached        job.cancel()    }    fun login(request: LoginRequest) = launch { // launching a coroutine        val result = repo.loginUser(request) // calling 'loginUser' function will not block the Main Thread, it suspends the coroutine        //use result, update UI        when (result) {            is Success<LoginResponse> -> { /* update UI when login success */ }             is Error -> { /* update UI when login error */ }        }    }}
总结

以上是内存溢出为你收集整理的java-以正确的方式使用协程全部内容,希望文章能够帮你解决java-以正确的方式使用协程所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1081817.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-27
下一篇 2022-05-27

发表评论

登录后才能评论

评论列表(0条)

保存