我应该在ViewModel中包含LifecycleOwner吗?

时间:2018-01-23 07:15:27

标签: android mvvm android-viewmodel

目前需要LifecycleOwner才能让我创建一个观察者。

我有代码在ViewModel中创建一个Observer,所以我在片段中检索ViewModel时附加了LifecycleOwner。

根据Google的文档。

警告:ViewModel绝不能引用视图,生命周期或任何可能包含对活动上下文的引用的类。

我是否打破了这个警告?如果我这样做了,你建议我以什么方式移动我的观察者创建数据返回?

我只是做了一个观察者,所以我想知道它是否仍然有效。同样在Google的文档中也说过。

ViewModel对象可以包含LifecycleObservers,例如LiveData对象。

MainFragment

private lateinit var model: MainViewModel

/**
 * Observer for our ViewModel IpAddress LiveData value.
 * @see Observer.onChanged
 * */
private val ipObserver = Observer<String> {
    textIp.text = it
    hideProgressBar()
}

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    model = ViewModelProviders.of(this).get(MainViewModel::class.java)
    model.attach(this)
}

override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? =
        inflater?.inflate(R.layout.fragment_main, container, false)

override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    buttonRetrieveIp.setOnClickListener {
        showProgressBar()
        model.fetchMyIp().observe(this, ipObserver) //Here we attach our ipObserver
    }
}

override fun showProgressBar() {

    textIp.visibility = View.GONE
    progressBar.visibility = View.VISIBLE
}

override fun hideProgressBar() {

    progressBar.visibility = View.GONE
    textIp.visibility = View.VISIBLE
}

MainViewModel

private var ipAddress = MutableLiveData<String>()
private lateinit var owner: LifecycleOwner

fun attach(fragment: MainFragment) {
    owner = fragment
}

/**
 * For more information regarding Fuel Request using Fuel Routing and Live Data Response.
 * @see <a href="https://github.com/kittinunf/Fuel#routing-support">Fuel Routing Support</a>
 * @see <a href="https://github.com/kittinunf/Fuel#livedata-support">Fuel LiveData Support</a>
 * */
fun fetchMyIp(): LiveData<String> {

    Fuel.request(IpAddressApi.MyIp())
            .liveDataResponse()
            .observe(owner, Observer {

                if (it?.first?.statusCode == 200) {//If you want you can add a status code checker here.

                    it.second.success {

                        ipAddress.value = Ip.toIp(String(it))?.ip
                    }
                }
            })
    return ipAddress
}

更新1:改进了ViewModel,感谢@pskink建议使用转换。

private lateinit var ipAddress:LiveData<String>

/**
 * Improved ViewModel since January 23, 2018 credits to <a href="https://stackoverflow.com/users/2252830/pskink">pskink</a> <a href="
 *
 * For more information regarding Fuel Request using Fuel Routing and Live Data Response.
 * @see <a href="https://github.com/kittinunf/Fuel#routing-support">Fuel Routing Support</a>
 * @see <a href="https://github.com/kittinunf/Fuel#livedata-support">Fuel LiveData Support</a>
 * */
fun fetchMyIp(): LiveData<String> {

    ipAddress = Transformations.map(Fuel.request(IpAddressApi.MyIp()).liveDataResponse(), {

        var ip:String? = ""

            it.second.success {

                ip = Ip.toIp(String(it))?.ip
            }
        ip
    })

    return ipAddress
}

2 个答案:

答案 0 :(得分:2)

<强>假设:

  1. Fuel指的是您的ViewModel
  2. Fuel.request(IpAddressApi.MyIp())ViewModel
  3. 中的一种方法
  4. IpAddressApi.MyIp()没有对您LifecycleOwner
  5. 的引用

    如果一切都是真的,那么你就不会违反它。只要您没有将LifecycleOwner引用传递给ViewModel,您就是安全的!

    LifecycleOwner - 与活动或片段相关,因为它拥有各种Android生命周期,例如onCreate,onPause,onDestroy等

答案 1 :(得分:1)

不。如果您希望观察ViewModel内部某些LiveData的变化,可以使用无需LifecicleOwner的observeForever()。 记住要在ViewModels onCleared()事件上删除此观察器:

val observer = new Observer() {
  override public void onChanged(Integer integer) {
    //Do something with "integer"
  }
}

...

liveData.observeForever(observer);

...

override fun onCleared() {
    liveData.removeObserver(observer) 
    super.onCleared()
}

很好地参考了observe LiveData的示例。