我目前需要 LifecycleOwner 才能创建观察者。
我有在 ViewModel 中创建 Observer 的代码,因此我在 Fragment 中检索 ViewModel 时附加了 LifecycleOwner。
根据谷歌的文档。
注意:ViewModel 绝不能引用视图、生命周期或任何可能持有对活动上下文的引用的类。
我是否打破了该警告,如果我打破了,您建议我以什么方式移动我创建的观察者以进行数据返回?
我只做了一个观察者,所以我想知道它是否仍然有效。因为也在谷歌的文档中也说过。
ViewModel 对象可以包含 LifecycleObservers,例如 LiveData 对象。
主要片段
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
}
主视图模型
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
}