【问题标题】:Kotlin - Multi Thread with RetrofitKotlin - 带改造的多线程
【发布时间】:2021-11-01 03:37:24
【问题描述】:

我在一个片段中有超过 5 个 api 调用。这样做,应用程序的性能加载会变慢。

所以我打算让它与 kotlin 并行运行。如何在我的代码中使用执行器、线程。

我以以下格式实现了 api。

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    viewModel.callApiOne()
    viewModel.callApiTwo()
    viewModel.callApiThree()

    viewModel.getResponseInViewModel().observe(this.viewLifecycleOwner, Observer {
        if (it.errorResponse?.code() == 200) {
            
        }
    })
}

ViewModel.kt

fun callApiOne() {
    repository.callApiOne()
}
fun getResponseInViewModel(): MutableLiveData<Resource<Model>> {
    respp = repository.getResponse()
    return respp
}

Repository.kt

private val resp by lazy { MutableLiveData<Resource<Model>>() }
  
   fun callApiOne() {
        val api = AppMain.restClient?.services?.callApiOne()
        api?.enqueue(object : Callback<Model> {
            override fun onFailure(call: Call<Model>, t: Throwable) {
                resp.postValue(Resource.failure(t.message!!, null))
            }

            override fun onResponse(
                call: Call<Model>,
                response: Response<Model>
            ) {
                if (response.isSuccessful) {
                    resp.postValue(Resource.successResp(response))
                } else {
                    resp.postValue(Resource.errorresponse(response))
                }
            }

        })

    }
    
    fun getResponse(): MutableLiveData<Resource<Model>> = resp 

【问题讨论】:

  • 您可以使用async一次调用5个api。更多信息:developer.android.com/kotlin/coroutines/…
  • 这些不是已经并行运行了吗?你enqueue他们,所以 Retrofit 自己并行处理异步工作。你在 LiveData 中得到你的结果,所以它不会阻塞主线程。但是即使有三个不同的请求,您也只显示了一个 LiveData,所以也许您省略了太多代码,我们无法判断您要做什么。
  • 但性能仍然很慢。是的,我省略了太多代码

标签: android kotlin retrofit2 android-livedata observer-pattern


【解决方案1】:

在这种情况下你应该使用协程。

例子:

MyFragment : Fragment(), CoroutineScope by MainScope() {
...

    private fun init() {
       launch { // starts a coroutine on main thread
          viewModel.fooSuspend()
       }
    }
}


MyViewModel : ViewModel() {
...

    suspend fun fooSuspend() {
       withContext(Dispatchers.IO) { //do on IO Thread
          doIOHaveOperation()
       }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-07
    • 2020-01-21
    • 1970-01-01
    • 2020-01-06
    • 2020-02-22
    • 1970-01-01
    • 2021-05-25
    • 2016-01-31
    相关资源
    最近更新 更多