我有一个工作活动(TwalksRouteActivity),它接受来自包(从片段传递)的记录id (routeID),从我的存储库(routesRepository)中提取相关的记录,并将相关的值/列(routeName)传递给我的UI。这可以很好地工作。然而,正如我所理解的最佳实践(我正在学习Android开发),对我的存储库的调用应该在ViewModel中进行,而不是在活动中。这是正确的吗?我已经尝试过,但失败了,我真的很感激如何做这件事的一些帮助。
TwalksRouteActivity:
class TwalksRouteActivity() : AppCompatActivity() {
private lateinit var viewModel: RouteViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//Log.i("CWM","Called ViewModelProvider")
//viewModel = ViewModelProvider(this).get(RouteViewModel::class.java)
var bundle: Bundle? = intent.extras
var routeID = bundle?.getInt("routeID")
lifecycleScope.launch (Dispatchers.Main) {
val database = getDatabase(application)
val routesRepository = RoutesRepository(database)
val selectedRoute = routesRepository.getRoute(routeID)
val routeName = selectedRoute.routeName
Log.d("CWM", routeName.toString())
setContentView(R.layout.route_detail)
val routeName_Text: TextView = findViewById(R.id.routeName_text)
routeName_Text.text = routeName.toString()
val routeID_Text: TextView = findViewById(R.id.routeID)
routeID_Text.text = routeID.toString()
}
}}
发布于 2021-01-18 03:28:01
你是对的。Best practices包含ViewModel的概念,它处理业务逻辑(您的存储库)和使用或/和显示数据的活动或片段之间的通信。你可以在ViewModel Overview上查看安卓开发者视图模型的官方文档。还有guide to app architecture。检查下图:

正如您所看到的,它描述了数据驱动的通信流,正如您所说的,ViewModel将调用获取数据的存储库函数。然后,ViewModel将为活动提供可以观察到的变量和/或函数(例如:LiveData),并触发活动将采用的事件,以便在UI中进行其状态更改/数据呈现(这称为反应式模式)。
你应该看看这些codelab (来自谷歌的免费课程):Incorporate Lifecycle-Aware Components和Android Room with a View - Kotlin (虽然它主要涵盖Room Library,但codelab使用了谷歌推荐的ViewModel和安卓的最佳实践)。另外,你可以查看这篇文章:ViewModels and LiveData: Patterns + AntiPatterns。
我可以写很多代码,但我认为这超出了这个答案的范围。我也在学习,我的方法是首先了解这些东西是如何工作的,以及为什么这些东西被称为“最佳实践”。
https://stackoverflow.com/questions/65763431
复制相似问题