Search code examples
androidkotlinretrofitget-request

Returns null getrequest retrofit kotlin


I have this function in my viewmodel and I want to retrieve a list of locations with a get Request. But when I call the function fetchAllLocations from the fragment this function returns null. But in the onResponse method the list locations isn't null. I don't know why locations is null outside of the onResponse method.

      fun fetchAllLocations(): List<Location>?
            {
        
                val call = apiInterface?.fetchAllLocation()
                var locations: List<Location>?  = null
        
                call?.enqueue(object : Callback<List<Location>> {
        
                    override fun onResponse(call: Call<List<Location>>, response: Response<List<Location>>) {
                        locations = response.body()
        
        
        
                    }
        
                    override fun onFailure(call: Call<List<Location>>, t: Throwable) {
                        
                    }
                })
                return locations
            }
        }

Solution

  • Add this live data in your viewmodel

       val locationLiveData by lazy { MutableLiveData<<List<Location>>() }
            
        fun fetchAllLocations(){
                
                        val call = apiInterface?.fetchAllLocation()
                        call?.enqueue(object : Callback<List<Location>> {
                
                            override fun onResponse(call: Call<List<Location>>, response: Response<List<Location>>) {
                                locations = response.body()
                                locationLiveData.postValue(locations)
                            }
                
                            override fun onFailure(call: Call<List<Location>>, t: Throwable) {}
                        })
                    }
       }
    

    Observe this live-data from your fragment class.

    viewModel.locationLiveData.observe(viewLifecycleOwner, Observer {
                //here you will get list
            })
    

    Ref Project : https://github.com/droiddevgeeks/MovieSearch ( Java) https://github.com/droiddevgeeks/TrendingRepo ( Kotlin)