【问题标题】:How to return value from coroutine scope如何从协程范围返回值
【发布时间】:2020-11-07 23:10:25
【问题描述】:

有没有办法从协程作用域返回值?比如这样:

suspend fun signUpUser(signUpData : SignUpUserRequest) : User {

CoroutineScope(Dispatchers.IO).launch() {

        val response = retrofitInstance.socialSignUP(signUpData)
        if (response.success) {
            obj = response.data
        } else {
                obj = response.message
        }
    }.invokeOnCompletion {
        obj = response.message
    }

    return obj
}

问题是一旦调用 signupUser 函数,返回 obj 挂起语句立即运行,而不是响应值。它没有按顺序运行,我期望的是第一个响应来,然后函数返回 obj 但它没有发生。为什么?

我尝试了运行阻塞,它达到了目的,但是有没有更好的方法来执行相同的任务而不阻塞运行?还是可以?

提前致谢!

【问题讨论】:

  • 您使用CoroutineScope 的方式破坏了结构化并发,因为启动的协程不是当前协程的子。如果要指定调度程序,请使用launch(Dispatchers.IO)

标签: android kotlin kotlin-coroutines coroutinescope


【解决方案1】:

您可以使用withContext 函数在后台线程中运行代码并返回一些结果:

suspend fun signUpUser(signUpData : SignUpUserRequest): User = withContext(Dispatchers.IO) {    
    val response = retrofitInstance.socialSignUP(signUpData)
    if (response.success) response.data else response.message
}

【讨论】:

  • 为什么我不能使用 CoroutineScope?
  • @blackHawk 你可以 CoroutineScope(Dispatchers.IO).async { /* return last line */ }.await() 但这并没有为此进行优化,而且每次调用函数时都创建 CoroutineScope 是个坏主意。
  • @AnimeshSahu 如何向这个协程添加异常或在完成时调用?
【解决方案2】:

如果您需要并行运行作品,则可以使用 coroutineScopeasync 协程构建器函数。但是,在您的情况下,您只有一个请求,因此它可能是 sequantial。如上一个答案所述,您可以使用withContext。这是docs的小解释:

使用给定的协程上下文调用指定的挂起块, 暂停直到完成,并返回结果。

suspend fun getUser(signUpData: SignUpUserRequest): User = withContext(Dispatchers.IO) {
    // do your network request logic here and return the result
}

请注意,当您使用带有函数的表达式主体时,请始终尝试显式注释返回类型。

编辑

协程使用常规的 Kotlin 语法来处理异常:try/catch 或像 runCatching 这样的内置辅助函数(在内部使用 try/catch)。 请注意总会抛出未捕获的异常。但是,不同的协程构建器以不同的方式处理异常。阅读official documentation 或其他来源(如this)总是好的。

【讨论】:

  • 如何向这个协程添加异常或在完成时调用?
  • @blackHawk 我编辑了答案。请看一下,如果它不适合你,请告诉我。
  • 请解释一下,什么不起作用?如果需要,请使用适当的详细信息更新您的问题。
【解决方案3】:

在 Google 代码实验室 "Load and display images from the Internet" 中,有一个很好且非常优雅的 MutableLiveData 示例。

大纲:

  • 您使用 LiveData(内部)和 MutableLiveData(外部)制作了一个 ViewModel
  • 现在您可以直接在视图、片段或活动中使用数据

好处是这些数据是生命周期感知的,您可以将返回的值用于观察者。

class OverviewViewModel : ViewModel() {

    enum class MarsApiStatus { LOADING, ERROR, DONE }

    private val _status = MutableLiveData<MarsApiStatus>()
    val status: LiveData<MarsApiStatus> = _status

    private val _photos = MutableLiveData<List<MarsPhoto>>()
    val photos: LiveData<List<MarsPhoto>> = _photos

    /**
     * Call getMarsPhotos() on init so we can display status immediately.
     */
    init {
        getMarsPhotos()
    }

    /**
     * Gets Mars photos information from the Mars API Retrofit service and updates the
     * [MarsPhoto] [List] [LiveData].
     */
    private fun getMarsPhotos() {
        viewModelScope.launch {
            _status.value = MarsApiStatus.LOADING
            Log.d(TAG, "loading")
            try {
                _photos.value = MarsApi.retrofitService.getPhotos()
                _status.value = MarsApiStatus.DONE
                Log.d(TAG, "done")
            } catch (e: Exception) {
                _status.value = MarsApiStatus.ERROR
                _photos.value = listOf()
                Log.d(TAG, "error")
            }
        }
    }
}

您可以通过观察它们或直接在这样的视图中使用它们来使用状态或照片值:

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/photos_grid"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:listData="@{viewModel.photos}"
        app:spanCount="2"
        tools:itemCount="16"
        tools:listitem="@layout/grid_view_item" />

...在您“注册”并连接 f.ex 中的所有内容之后。关于片段,像这样:

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {

    try {
        val binding = FragmentOverviewBinding.inflate(inflater)
        //val binding = GridViewItemBinding.inflate(inflater)

        // Allows Data Binding to Observe LiveData with the lifecycle of this Fragment
        binding.lifecycleOwner = this

        // Giving the binding access to the OverviewViewModel
        binding.viewModel = viewModel

        binding.photosGrid.adapter = PhotoGridAdapter()

        return binding.root
    } catch (e: Exception) {
        Log.e("OverviewFragment", "${e.localizedMessage}")
    }
    return null
}

【讨论】:

    猜你喜欢
    • 2022-07-05
    • 2023-01-27
    • 2021-08-17
    • 2015-04-13
    • 1970-01-01
    • 2020-07-09
    • 1970-01-01
    • 2021-07-16
    • 2020-06-23
    相关资源
    最近更新 更多