I've been following documentation to use location for a weather app. I've followed the instructions as specified for MainActivity
but would like to use this location information for making API calls.
I've structured my app after a CodeLab involving RetroFit2 and Moshi. I've declared a network
package and am working in a ApiService
class contained therein. How can I access the location object defined in MainActivity
from within ApiService
?
com.example.app.MainActivity:
private lateinit var fusedLocationClient: FusedLocationProviderClient
override fun onCreate(savedInstanceState: Bundle?) {
// ...
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
}
com.example.app.network.ApiService:
// how to access fusedLocationClient here?
private const val BASE_URL =
"https://api.open-meteo.com/v1/forecast?latitude=52.52&longitude=13.41¤t_weather=true"
private val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
private val retrofit = Retrofit.Builder()
.addConverterFactory(MoshiConverterFactory.create(moshi))
.baseUrl(BASE_URL)
.build()
CodePudding user response:
There're some ways you could accomplish this. The easiest one is have this API call on the MainActivityViewModel, so you could send as a parameter all the information you want. It would be something like this:
private lateinit var fusedLocationClient: FusedLocationProviderClient
override fun onCreate(savedInstanceState: Bundle?) {
// ...
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
viewModel.makeCall(fusedLocationCient)
}
And on the viewModel
ViewModel: ViewModel() {
fun makeCall(fusedLocationClient: LocationClient) {
// I don't know how you created this ApiService,
// but you should access it here
ApiService().makeCall(fusedLocationClient)
}
}
The second one (don't think you're gonna need this) is to have a Singleton with this Location data, and get it on the class you want. You could use Koin to inject these classes.