android viewmodel observer回调多次的问题

/***
ViewModels can also be used as a communication layer between different Fragments of an Activity.
 * Each Fragment can acquire the ViewModel using the same key via their Activity. This allows
 * communication between Fragments in a de-coupled fashion such that they never need to talk to
 * the other Fragment directly.
 * 
 * public class MyFragment extends Fragment {
 *     public void onStart() {
 *         UserModel userModel = new ViewModelProvider(requireActivity()).get(UserModel.class);
 *     }
 * }
 ***/

原因:fragment创建viewmodel时,创建了activity的viewmodel,所以生成fragment时回调的是activity的viewmodel
解决:把ViewModelProvider(requireActivity()).get(UserModel.class)改成
ViewModelProvider(this).get(UserModel.class)

你可能感兴趣的:(android,java,android,studio)