Reputation: 135
I'm trying to get Weather infomation by using api.
To use weather api I need Location information.
So I have to use Location Manager.
But in this project I use MVVM design pattern.
So I can't get Location Manager in ViewModel. And also I can't request permission in viewmodel.
How can I get Location Manager in view model and how can I use onRequestPermissionsResult() in ViewModel?
And requesting permission in view model and using onRequestPermissionsResult() in ViewModel is right way?
This is my code.
public class MAgencyViewModel extends ViewModel{
private final String TAG = "MAgencyViewModel";
//이 클래스에서는 Model과 통신하여서 날씨 정보를 받아온다.
private MutableLiveData<ShortWeather> sw;
private MAgencyRepo maRepo;
private LocationManager lm;//핸드폰에 있는 gps관련 기기와 상호작용하기 위해서
private GpsTransfer gpt;
private GeoInfo gi;
//여기서 이제 위치정보를 가지고 날씨정보 API를 호출하는 부분
public void init(GeoInfo gi){
if(sw != null){
return;
}
//I want to get Location information in here
maRepo = MAgencyRepo.getInStance();
sw = maRepo.getWeather(gi); // this part is calling a weather api
Log.i(TAG,"API Connection finish");
}
public LiveData<ShortWeather> getWeather(){
return sw;
}
}
Upvotes: 2
Views: 1619
Reputation: 7670
I would try to make ViewModel as platform independent as possible and especially Context
free.
So in this case I'd request this on the View layer (Activity, Fragment), since getting the LocationManager
can be done with getSystemService() which is a function of Context
. Then delegate the events, such as onRequestPermissionsResult()
to the ViewModel
Upvotes: 6