[英]Kotlin singleton getter in ViewModel
I'm studying Android Architecture Components. 我正在研究Android体系结构组件。 How to implement singleton getInstance() method using Kotlin ?
如何使用Kotlin实现单例getInstance()方法? I did this using Java-like style (getLocation), but it is not kotlin-like.
我使用类似Java的样式(getLocation)进行了此操作,但它不是类似kotlin的样式。
class LocationViewModel: ViewModel() {
lateinit var locationData: MyLocationListener
fun getLocation(context: Context): MyLocationListener {
locationData = MyLocationListener(context)
return locationData
}
}
You shouldn't really use a make ViewModels a singleton - they should be scoped to the lifecycle of the Activity/Fragment in which they are created. 您不应该真正使用make ViewModels单例-它们的作用域应限于创建它们的Activity / Fragment的生命周期。
If you want to expose the MyLocationListener instance you could use the AndroidViewModel class - this provides you with access to the application class which you can use as the Context. 如果要公开MyLocationListener实例,则可以使用AndroidViewModel类-这使您可以访问可用作Context的应用程序类。
class LocationViewModel(application: Application): AndroidViewModel(application) {
val locationData = MyLocationListener(application)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.