如何使用Android的体系结构组件完成ViewModel的活动? [英] How to finish activity from ViewModel using Android's architecture components?

查看:115
本文介绍了如何使用Android的体系结构组件完成ViewModel的活动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出如何以最佳方式完成ViewModel中的Activity.我找到了一种使用LiveData对象并发出信号"的方法.

I try to figure out how to in best way finish an Activity from ViewModel. I found the one way to do this using LiveData object and emitting "signal".

我怀疑此解决方案会产生开销.那么是正确的解决方案,还是我应该使用更准确的解决方案?

I have a doubt that this solution has a overhead. So is it right solution or I should use more accurate?

下面是一个例子:假设在一个应用程序中有一个活动MainActivity并查看如下模型:

So go to example: let's suppose that in an app is an activity MainActivity and view model like below:

 class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val model = ViewModelProviders.of(this).get(MainViewModel::class.java)

        model.shouldCloseLiveData.observe(this, Observer { finish() })

    }
 }

作为MainActivity的伴侣,还有一个MainViewModel,如下所示:

and as a companion to the MainActivity is a MainViewModel like below:

class MainViewModel(app: Application) : AndroidViewModel(app) {

  val shouldCloseLiveData = MutableLiveData<Void>()

  fun someAction(){
    shouldCloseLiveData.postValue(null)
  }

}

推荐答案

我分享您的感觉,该解决方案看起来不整洁有两个原因. First 使用MutableLiveData对象来表示事件是一种解决方法.没有数据被更改. 第二将LiveData暴露在视图模型外部通常会违反封装的原理.

I share your feelings that this solution does not look tidy for two reasons. First using a MutableLiveData object to signal an event is a workaround. No data is changed. Second exposing LiveData to the outside of the view model violates the principle of encapsulation in general.

我仍然对这个丑陋的android概念感到惊讶.他们应该提供观察视图模型的选项,而不是内部的LiveData对象.

I am still surprised about this ugly concept of android. They should provide an option to observe the view model instead of it's internal LiveData objects.

我尝试了WeakReference来实现观察者模式.这是不稳定的. WeakReference的引用对象以不可预测的方式丢失(null),在大多数情况下,无法调用finish().这令人惊讶,因为我认为该活动在运行时不会被垃圾收集.

I experimented with WeakReferences to implement the observer pattern. This was unstable. In an unpredictable manner the referent of the WeakReference was lost (null), in wich cases it was not possible to call finish(). This was surprising as I don't think the activity is garbage collected while running.

因此,这是排除在外的部分答案.实施为WeakReference的观察者模式似乎无法替代您的建议.

So this is an partly answer by exclusion. The observer pattern implemented as WeakReference seems to be no alternative to your suggestion.

我是否想通过硬引用合法地实现观察者模式,是否在onStop()onDestroy()期间删除了引用.我问了这个问题这里.

A wonder if it is legitimate implement the observer pattern by hard references, if I remove the references during onStop(), or onDestroy(). I asked this question here.

这篇关于如何使用Android的体系结构组件完成ViewModel的活动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆