Improving the way our app handles network requests
Our application now successfully obtains data from the server dynamically, at runtime. Unfortunately, we have made two major mistakes in our code, and both are related to how the app handles the requests. Let's identify them:
- First, we are not canceling our network request as a cleanup measure. If our UI component that is bound to
RestaurantsViewModel
– in our case,MainActivity
– is destroyed before the response from the server can arrive (for example, if the user navigates to another activity), we could potentially create a memory leak. This is because ourRestaurantsViewModel
would still be tied to theCallback<List<Restaurant>>
object, which waits for the server's response. Due to this, the garbage collector won't free up the memory associated with both of their instances. - Secondly, we are not triggering the network request from a controlled environment. The
viewModel.getRestaurants...