【问题标题】:how to implement MVVM如何实现 MVVM
【发布时间】:2020-02-09 05:34:18
【问题描述】:

我想使用 MVVM 架构,我有一个视图寻呼机,它有两个片段。每个片段都有一个 RecyclerView。我创建了一个扩展 AndroidViewModel 的视图模型类,因为我需要将上下文传递给我的存储库,该存储库从 API 类获取数据,该 API 类使用 volley 从服务器获取数据。我预计当旋转我的手机时,我的 ViewModel 类不会被调用,但根据我设置的日志,当我旋转手机时,似乎一切都会重新开始。

还好吗?还是我有什么问题?

这是我的片段代码:

val viewModel: Fragment1ViewModel =
        ViewModelProviders.of(this).get(Fragment1ViewModel(Application())::class.java)


    viewModel.getData().observe(this, Observer {
        Log.i("Log","data is Loaded in activity")
    })

这是 ViewModel 类代码:

class Fragment1ViewModel(application: Application) : AndroidViewModel(application) {
private val repository=Repository(application)

fun getData():LiveData<String>{
    Log.i("Log","get data in view model")
    return repository.getListItem()
}

}

这是我的存储库代码:

class Repository(private val context: Context) {
companion object {
    private lateinit var serverFetch: ServerFetch
}


private fun setContext() {
    serverFetch = ServerFetch(context)
}


fun getListItem():LiveData<String>{
    setContext()
    return serverFetch.getData()
}

}

这是我的 ServerFetch 类,它用作存储库的 API:

class ServerFetch(private val context: Context) {

private val api: String = "https://jsonplaceholder.typicode.com/posts"

private val result = MutableLiveData<String>()


private fun connect() {

    val request = StringRequest(Request.Method.GET, api, Response.Listener {
        Log.i("Log", "ServerFetch Successfully")
        result.value = it

    }, Response.ErrorListener {
        Log.i("Log", "ServerFetch field: ${it.toString()}")
    })

    val queue = Volley.newRequestQueue(context)
    queue.add(request)

}


fun  getData(): LiveData<String> {
    connect()
    return result
  }
}

这是我的应用程序首次运行时的日志:

 I/Log: get data in view model
 I/Log: ServerFetch Successfully
 I/Log: data is Loaded in activity

这是我旋转手机时的日志

 I/Log: get data in view model
 I/Log: ServerFetch Successfully
 I/Log: data is Loaded in activity

【问题讨论】:

    标签: kotlin mvvm android-livedata android-viewmodel


    【解决方案1】:

    您应该在视图模型的实例化时获取它。

    视图模型:

    class Fragment1ViewModel(application: Application) : AndroidViewModel(application) {
        private val repository = Repository(application)
        val data = repository.getListItem()
    }
    

    片段:

    viewModel.data.observe(this, Observer {
        Log.i("Log","data is Loaded in activity")
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-30
      • 2011-06-03
      相关资源
      最近更新 更多