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

How to properly call network fetching function from view model

我应该如何调用 ViewModel 中的函数 QueryUtils.fetchData(REQUEST_URL),它 returns 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();
    }
}

稍微重写您的视图模型class:

 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();
}
}

请试试这个并告诉我

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