Can I use ViewModel to send data to the server?

杀马特。学长 韩版系。学妹 提交于 2019-12-11 01:09:44

问题


Currently, I am using ViewModel to load a list of Shows in my app. Then, I display it in the main screen. It survives to configuration changes and does not provoke memory leaks since ViewModel has this features.

Now I need to do something a bit different. I need to log in a user making a network call to an endpoint using retrofit 2 and rxjava 2, he will type the email and password, and then will be redirected to the MainActivity. Second, I also need to update the user information, he types his new information and then I send to the server.

May I use ViewModel to log in a user or to update user information? If not, what sould I use instead?

What I need

This retrofit 2 call should survive to configuration changes, as rotating the screen, and it can not cause memory leak.

What I tried

  1. Calling retrofit using enqueue() method in the MainActivity. Obs: This approach is not good because it puts to much things in the ui class, it provokes memory leaks.

  2. Using static inner classes. Obs: It does not survive to configuration changes, as I need to cancel the task in onDestroy().

  3. MVP seems fine to login a user.


回答1:


You can check google sample project, specifically this class

https://github.com/googlesamples/android-architecture/blob/todo-mvvm-databinding/todoapp/app/src/main/java/com/example/android/architecture/blueprints/todoapp/addedittask/AddEditTaskViewModel.java

Usually you would trigger the network operation in the model view, while the code for implementing the network logic is written in a different class (ApiManager for example), and then get the results in your ViewModel

  • LoginViewModel will have an object of some network manager class

  • When you click login, the viewmodel will call networkManager.performLogin()

  • Results are then passed to the viewmodel (RxJava is handy in here).

  • In your ViewModel do whatever processing you need when you receive the results



来源:https://stackoverflow.com/questions/52332326/can-i-use-viewmodel-to-send-data-to-the-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!