public class LocationLiveData extends LiveData<Location> {
LocationService.LocationListener locationListener = new LocationService.LocationListener() {
@Override
public void onLocationChanged(Location location) {
setValue(location);
}
};
@Override
protected void onActive() {
LocationService.addListener(locationListener);
}
@Override
protected void onInactive() {
LocationService.removeListener(locationListener);
}
}
private LiveData<String> mText = Transformations.map(mIndex, new Function<Integer, String>() {
@Override
public String apply(Integer input) {
ExecutorService service = Executors.newCachedThreadPool();
Callable<String> callableTask = () -> GoogleSearchJava.Search("Поисковое слово", "10");
Future<String> future = service.submit(callableTask);
try {
Log.println(Log.DEBUG,"GoogleSearch",future.get());
return future.get();
} catch (InterruptedException | ExecutionException e) {
Log.println(Log.ERROR, "GoogleSearch", e.getMessage() + "\n" + e.getStackTrace());
return e.getMessage() + "\n" + e.getStackTrace();
}
}
});
public class SearchLiveData extends LiveData<String> {
private static SearchLiveData instance;
private int index;
public static SearchLiveData getInstance(int index) {
if (instance == null) {
instance = new SearchLiveData(index);
}
return instance;
}
private SearchLiveData(int index){
this.index = index;
}
@Override
public void postValue(String value) {
try {
value = GoogleSearchJava.Search(index + "Поиск", "10");
} catch (IOException e) {
e.printStackTrace();
value = e.getMessage() + "\n" + e.getStackTrace();
}
super.postValue(value);
}
}
public class PageViewModel extends ViewModel {
private MutableLiveData<Integer> mIndex = new MutableLiveData<>();
private SearchLiveData mText = (SearchLiveData) Transformations.switchMap(mIndex, new Function<Integer, LiveData<String>>() {
@Override
public LiveData<String> apply(Integer input) {
return SearchLiveData.getInstance(input);
}
});
public void setIndex(int index) {
mIndex.setValue(index);
}
public LiveData<String> getText() {
return mText;
}
}
private LiveData<String> mText = Transformations.map(mIndex, new Function<Integer, String>() {
@Override
public String apply(Integer input) {
ExecutorService service = Executors.newCachedThreadPool();
Callable<String> callableTask = () -> GoogleSearchJava.Search("Поисковое слово", "10");
Future<String> future = service.submit(callableTask);
String response = "";
try {
response = future.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
return response;
}
});