Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Navigation in Android (四)——share ViewModel in Navigation #127

Open
soapgu opened this issue Mar 25, 2022 · 0 comments
Open

Navigation in Android (四)——share ViewModel in Navigation #127

soapgu opened this issue Mar 25, 2022 · 0 comments
Labels
mvvm This issue or pull request already exists 安卓 安卓

Comments

@soapgu
Copy link
Owner

soapgu commented Mar 25, 2022

  • 在导航中传输数据

安卓导航数据有两种方法

  • 在导航图里面增加parameter
    这种方式在Navigation in Android (二)里面介绍过了,一般只有基础类型而且需要一一罗列。另外只支持通过Bundle来传输的,这个对象只支持小数据,数据量大了肯定吃不消

  • 通过共享ViewModel实现
    如果严格按照MVVM架构整合性比较好。下面主要介绍这种方式。

  • 如果让ViewModel在导航中共享

  • 共享媒介
    ViewModelProvider(@NonNull ViewModelStoreOwner owner)
    ViewModel需要ViewModelStoreOwner,ViewModelStoreOwner就是这个共享媒介

  • 在 Fragment 之间共享数据
    像这种是通过同一个Activity来共享ViewModel的

但是我一个导航图里面的上下游Fragment怎么共享ViewModel那

ViewModel 支持 - 您可以将 ViewModel 的范围限定为导航图,以在图表的目标之间共享与界面相关的数据。

官网就是提了一嘴,只能自己试验了

代码实现

   @NonNull
   @Override
   protected ViewModelStoreOwner provideViewModelStoreOwner() {
       return NavHostFragment.findNavController(this).getViewModelStoreOwner(R.id.nav_graph);
   }

   @Nullable
   @Override
   public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
       this.viewModel =  new ViewModelProvider(this.provideViewModelStoreOwner()).get(classOfVM);
       ViewDataBinding binding = DataBindingUtil.inflate( inflater , layoutId , container ,false );
       binding.setVariable( this.variableId , this.viewModel );
       binding.setLifecycleOwner(this);
       for( Pair<Integer, Object> each : getExtraVariableSource() ){
           binding.setVariable( each.first , each.second );
       }
       return binding.getRoot();
   }

就是通过NavController的api来获取导航图的媒介
共享ViewModel的Fragment都使用一样的代码,就可以拿到同一个ViewModel

  • 一些其他问题

共享数据的问题是解决了,就是ViewModel的生命周期没延长了,就是整个导航控件不死,ViewModel是不会被释放的。
目前暂时没问题。如果有需要可能需要写代码手工释放

@soapgu soapgu added mvvm This issue or pull request already exists 安卓 安卓 labels Mar 25, 2022
@soapgu soapgu changed the title Navigation in Android (三)——share ViewModel in Navigation Navigation in Android (四)——share ViewModel in Navigation Mar 26, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
mvvm This issue or pull request already exists 安卓 安卓
Projects
None yet
Development

No branches or pull requests

1 participant