Home > Software design >  Which lifecycle method should I place my network call so it doesn't get called again when the s
Which lifecycle method should I place my network call so it doesn't get called again when the s

Time:12-14

I'm trying to learn MVVM architecture by having displaying a list after querying an API. I'm a bit unsure on how I should deal with the issue of rotating my device because once I rotate it, my onCreate method is called again and a second query to the API is called. Where should I place my network call so it doesn't perform another query when the screen orientation changes?

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        viewModel = new ViewModelProvider(this).get(PostViewModel.class);

        adapter = new PostAdapter(viewModel.getListPosts());
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);

        viewModel.getGetPostsLiveData().observe(this, listPosts -> {
            Log.d(TAG, "onCreate: Called...");
            adapter.notifyDataSetChanged();
        });

        viewModel.getPosts();

    }

My method viewModel.getPosts(); performs the query and is called again when the device screen orientation changes.

According to this answer:

https://stackoverflow.com/a/28853252/11110509

onPause();
onSaveInstanceState();
onStop();
onDestroy();

onCreate();
onStart();
onResume();

This is the lifecycle of a screen orientation change. For those 3 methods, onCreate, onStart, and onResume they are called once when the app opens and are called again everytime the screen changes. So I am unsure where I should place request to make the network call at.

CodePudding user response:

If it's a one time call you could just call it from your ViewModel.

init {
getPosts()
}
  • Related