【问题标题】:Using viewmodelScope launch with lifecycle transformations使用带有生命周期转换的 viewmodelScope 启动
【发布时间】:2019-09-24 12:02:55
【问题描述】:

我在我的项目中使用以下版本 -

implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0-alpha04"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.2.0-alpha04"

所以在我的视图模型类中,我这样做了 -

fun initView() =
        Transformations.map(domain.performOperation()) {
            when (it) {
                ...
            }
        }

我的 View Model 类扩展了 Base View Model 类,Base View Model 类看起来像这样 -

open class BaseViewModel(private val coroutineCtx: CoroutineContext = Dispatchers.Main) :
    ViewModel(),
    CoroutineScope {

    private val job = SupervisorJob()

    override val coroutineContext: CoroutineContext
        get() = coroutineCtx + job

    override fun onCleared() {
        super.onCleared()
        job.cancel()
    }
}

这似乎可行,但我想即兴创作我的代码并摆脱 Base View Model 类中的样板协程代码。所以我想在 My View Model 类中直接使用viewModelScope.launch。但是如何将它与Transformations.map 一起使用?

【问题讨论】:

  • @MrVasilev 是的,但没有提到如何将它与 Transformations.map 一起使用
  • 您确定需要 Transformations.map 吗?你的方案是什么,你想达到什么目标?你能分享更多你的代码吗?
  • @MrVasilev 是的,我使用 Transformations.map,因为我的域返回了一个密封的 APIResult 类,我将其映射到 ViewModel 类中的 ViewState 并将其提供给视图
  • 所以,如果我理解正确,您的“域”包含您的业务逻辑并对某些服务器进行 REST 调用并返回 LiveData,然后根据此结果更新您的视图,对吗?

标签: android kotlin android-livedata android-viewmodel


【解决方案1】:

所以,如果我的一切都正确,也许这样的解决方案可以帮助你:

在你的活动/片段中

lifecycleScope.launchWhenStarted {
        val apiResult = viewModel.initView()
        updateUI(apiResult)
        }

在您的视图模型中

private val apiDeferred = CompletableDeferred<LiveData<APIResult>>()

suspend fun initView(): LiveData<APIResult> {
        viewModelScope.launch(Dispatchers.IO) {
            val apiResult = domain.performOperation()
            artsDeferred.complete(arts)
        }
        return apiDeferred.await()
    }

您也可以在此处观看此视频:https://www.youtube.com/watch?v=BOHK_w09pVA&t=1230s(22 分钟后)

请说这是否适合您,我也可以建议使用最新技术协程、liveData 等的其他解决方案

【讨论】:

  • 是的,它可以工作,但我想要更多的 Transformations.map
猜你喜欢
  • 1970-01-01
  • 2021-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-01
  • 1970-01-01
  • 2020-07-20
  • 1970-01-01
相关资源
最近更新 更多