简体   繁体   中英

Android navigation component

android navigation component reload fragment , and observe mutable data again when navigate back from fragment to fragment , I tried single observe listener but nothing happen keep reloading and hitting api again

public class TermsFragment extends Fragment  {

private TermsViewModel termsViewModel;
private FragmentTermsBinding binding;

public View onCreateView(@NonNull LayoutInflater inflater,
                         ViewGroup container, Bundle savedInstanceState) {
    termsViewModel = new ViewModelProvider(this).get(TermsViewModel.class);
    termsViewModel.init(getContext());
    binding = FragmentTermsBinding.inflate(inflater, container, false);
    termsViewModel.terms.observe(getViewLifecycleOwner(), terms -> {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            binding.terms.setText(Html.fromHtml(terms.replaceAll("<img.+?>", ""), Html.FROM_HTML_MODE_COMPACT));
        } else {
            binding.terms.setText(Html.fromHtml(terms.replaceAll("<img.+?>", "")));
        }

    });

    View root = binding.getRoot();
    return root;
}

@Override
public void onDestroyView() {
    super.onDestroyView();
    binding = null;
  }
}

and my viewmodel Class

public class TermsViewModel extends ViewModel implements Onresponse {

public MutableLiveData<String> terms;

Context context=null;

public TermsViewModel() {
    terms = new MutableLiveData<>();

}

public  void  init(Context context){
    this.context=context;
    Map<String,Object> body=new HashMap<>();
    body.put("st", Api.app_data);
    body.put("id",1);
    body.put("lg",Constant.langstr);
    Constant.connect(context,Api.app_data,body,this::onResponse,false);
}

@Override
public void onResponse(String st, JSONObject object, int online) {
    if(object!=null) {
        try {
            terms.setValue(object.getString("data"));
        } catch (JSONException e) {
            e.printStackTrace();
        }

     }
  }

}

When you navigate back and forth the view does not survive but the fragment does . Thus you can move any initialization code to onCreate instead of onCreateView . onCreate is called once per fragment's lifetime.

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
 
    termsViewModel = new ViewModelProvider(this).get(TermsViewModel.class);
    termsViewModel.init(getContext());
}

This way you will:

  • create view model only once! It is crucial as replacing view model with a new instance discards all the data you have previously loaded;
  • call init only once in a lifetime of this fragment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM