Android ViewModel call Activity methods

前端 未结 3 576
执念已碎
执念已碎 2020-12-31 08:13

I\'m using android AAC library and Android databinding library in my project. I have AuthActivity and AuthViewModel extends android\'s ViewModel class. In some cases i need

3条回答
  •  [愿得一人]
    2020-12-31 08:25

    the most difficult part of MVVM is View model must not know about view and reference them

    This is quite strong restriction.

    You have some options about that

    1. View model methods receveing context argument

    You can make methods receveing context from view(this method is called from view).

    After you can instantiate context related variables.

    If you are aware about memory leak, just destroy it when view is pause or stop using Lifecycle aware AAC and reinstatiate when resume or start of Activity or Fragment.

    About onActivityResult, I think your solution is not bad because API support is like that.

    2. get context from view with data binding

    in layout xml, you can send view itself with event listener.

    Then you can receive view and retrieve context from view in Viewmodel

    3. Use AndroidViewModel

    AndroidViewModel class is same with ViewModel class without that has Application context.

    You can use Application Context with

    gerApplication()
    

    Thank you

提交回复
热议问题