Best practices and patterns in ViewModel + Data Binding. Is ObservableField in ViewModel OK?

微笑、不失礼 提交于 2019-12-04 09:53:12

You should consider splitting view-logic with business-logic.

Since you have a ViewModel using databinding and AAC to handle that you should also seperate the logic inside your view (layout).

Just pass two variables to your layout. One is the VievModel which handle business-logic like pressing a button and processing the logic, the second one is the View (fragment).

After that you can use

app:onRefreshListener="@{() -> yourViewFragment.refreshList()}"

and avoid having "context leaks" or a not working solution if there's currently no view subscribed.

Since the onRefreshListener is bound to a fragment its OK to pass that inside your fragment.

You shoudnt create a LiveData or ObservableField inside your ViewModel to handle that kind of operations because if you pause and resume the fragment you'r going to observe the LiveData again. That also means that you will get the last data delivered again.

Example which can be used in the ViewModel:

<Textview ... name="@{viewModel.dataOfYourModel}" onClick="@{viewModel.doNetworkCall}" />

Golden rule: Every package/import beginning with android.* should be NOT inside the viewmodel except the android.arch.* components.

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