如何从视图模型中正确调用网络获取函数



我应该如何调用函数QueryUtils.fetchData(REQUEST_URL(在ViewModel里面,它返回List<Earthquakes>。此代码以应有的方式获取数据,但它不会显示它,可能是因为它在获取数据之前已经设置了数据。

public class MainActivity extends AppCompatActivity {
private EarthquakeAdapter mEarthquakeAdapter;
private EarthquakeViewModel aEarthquakeViewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Redacted
aEarthquakeModel = ViewModelProviders.of(this).get(EarthquakeViewModel.class);
aEarthquakeViewModel.fetchEarthquakes().observe(this, new Observer<ArrayList<Earthquake>>() {
@Override
public void onChanged(ArrayList<Earthquake> earthquakes) {
if(earthquakes != null) {
mEarthquakeAdapter.clear();
mEarthquakeAdapter.addAll(earthquakes);
}
}
});
}
}

public class EarthquakeViewModel extends AndroidViewModel {
public MutableLiveData<ArrayList<Earthquake>> earthquakesData;
private ArrayList<Earthquake> earthquakes;
public EarthquakeViewModel(@NonNull Application application) {
super(application);
Log.i("EarthquakeViewModel", "EarthquakeViewModel constructor entered");
earthquakesData = new MutableLiveData<>();
doIt();
Log.i("EarthquakeViewModel", "EarthquakeViewModel constructor finished");
}
public LiveData<ArrayList<Earthquake>> fetchEarthquakes() {
earthquakesData.setValue(earthquakes);
return earthquakesData;
}
public void doIt() {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
earthquakes = (ArrayList<Earthquake>) QueryUtils.fetchData(REQUEST_URL);
}
});
thread.start();
}
}

你需要理解 muttableLiveData 中 setValue(( 和 postValue(( 的概念。当您在主线程中更新时,您必须使用函数 setValue(( 更新 MutableLive 数据,而在工作线程中您需要使用 postValue(( 时。希望这有帮助。以上答案满足您的要求。

稍微重写一下视图模型类:

public class EarthquakeViewModel extends AndroidViewModel {
public MutableLiveData<ArrayList<Earthquake>> earthquakesData;
private ArrayList<Earthquake> earthquakes;
public EarthquakeViewModel(@NonNull Application application) {
super(application);
Log.i("EarthquakeViewModel", "EarthquakeViewModel constructor entered");
earthquakesData = new MutableLiveData<>();
doIt();
Log.i("EarthquakeViewModel", "EarthquakeViewModel constructor finished");
}
public LiveData<ArrayList<Earthquake>> fetchEarthquakes() {
return earthquakesData;
}
public void doIt() {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
earthquakes = (ArrayList<Earthquake>) QueryUtils.fetchData(REQUEST_URL);
earthQuakesData.postValue(earthquakes);
}
});
thread.start();
}
}

请尝试这个并让我知道

相关内容

  • 没有找到相关文章

最新更新