在Android分页库中使用过滤器或搜索的最佳方法

时间:2019-12-20 14:38:42

标签: java android mvvm android-livedata android-paging

我进行了搜索,但没有找到适合我的情况的好的解决方案: 我需要过滤通过分页库生成的现有List<Article>,但无法弄清楚如何从 FeedActivity 类中的 FeedDataSource 类的api请求中检索实际的articleList。强>。我需要在 adapter.submitList(pagedList);

之前过滤实际列表

FeedDataSurce类

public class FeedDataSource extends PageKeyedDataSource<Long, Article>{

private static final String QUERY = "movies";
private static final String API_KEY = "079dac74a5f94ebdb990ecf61c8854b7";

private static final String TAG = FeedDataSource.class.getSimpleName();

private RestApi restApi;

private MutableLiveData networkState;

public FeedDataSource() {
    restApi = RestApiFactory.feedRequest();
    networkState = new MutableLiveData();
}

public MutableLiveData getNetworkState() {
    return networkState;
}

@Override
public void loadInitial(@NonNull LoadInitialParams<Long> params,
                        @NonNull LoadInitialCallback<Long, Article> callback) {

    networkState.postValue(NetworkState.LOADING);

    restApi.fetchFeed(QUERY, API_KEY, 1, params.requestedLoadSize)
            .enqueue(new Callback<FeedResponse>() {
                @Override
                public void onResponse(Call<FeedResponse> call, Response<FeedResponse> response) {
                    if(response.isSuccessful()) {
                        callback.onResult(response.body().getArticles(), null, 2l);
                        networkState.postValue(NetworkState.LOADED);

                    } else {
                        networkState.postValue(new NetworkState(NetworkState.Status.FAILED, response.message()));
                    }
                }

                @Override
                public void onFailure(Call<FeedResponse> call, Throwable t) {
                    String errorMessage = t == null ? "unknown error" : t.getMessage();
                    networkState.postValue(new NetworkState(NetworkState.Status.FAILED, errorMessage));
                }
            });
}

@Override
public void loadBefore(@NonNull LoadParams<Long> params,
                       @NonNull LoadCallback<Long, Article> callback) {

}

@Override
public void loadAfter(@NonNull LoadParams<Long> params, @NonNull LoadCallback<Long, Article> callback) {
    Log.d(TAG, "Loading Rang " + params.key + " Count " + params.requestedLoadSize);
    networkState.postValue(NetworkState.LOADING);

    restApi.fetchFeed(QUERY, API_KEY, params.key, params.requestedLoadSize).enqueue(new Callback<FeedResponse>() {
        @Override
        public void onResponse(Call<FeedResponse> call, Response<FeedResponse> response) {
            if(response.isSuccessful()) {
                callback.onResult(response.body().getArticles(), params.key + 1);
                networkState.postValue(NetworkState.LOADED);

            } else
                networkState.postValue(new NetworkState(NetworkState.Status.FAILED, response.message()));
        }

        @Override
        public void onFailure(Call<FeedResponse> call, Throwable t) {
            String errorMessage = t == null ? "unknown error" : t.getMessage();
            networkState.postValue(new NetworkState(NetworkState.Status.FAILED, errorMessage));
        }
    });
}

DataFactory类

public class FeedDataFactory extends DataSource.Factory {

private MutableLiveData<FeedDataSource> mutableLiveData;

public FeedDataFactory() {
    this.mutableLiveData = new MutableLiveData<>();
}

@Override
public DataSource create() {
    FeedDataSource feedDataSource = new FeedDataSource();
    mutableLiveData.postValue(feedDataSource);
    return feedDataSource;
}


public MutableLiveData<FeedDataSource> getMutableLiveData() {
    return mutableLiveData;
}

ViewModel

public class FeedViewModel extends ViewModel {

private Executor executor;
private LiveData<NetworkState> networkState;
private LiveData<PagedList<Article>> articleLiveData;

public FeedViewModel() {
    init();
}

private void init() {
    executor = Executors.newFixedThreadPool(5);

    FeedDataFactory feedDataFactory = new FeedDataFactory();

    networkState = Transformations.switchMap(feedDataFactory.getMutableLiveData(),
            dataSource -> dataSource.getNetworkState());


    PagedList.Config pagedListConfig = new PagedList.Config.Builder()
            .setEnablePlaceholders(true)
            .setInitialLoadSizeHint(20)
            .setPageSize(20)
            .build();

    articleLiveData = new LivePagedListBuilder(feedDataFactory, pagedListConfig)
            .setFetchExecutor(executor)
            .build();
}



public LiveData<NetworkState> getNetworkState() {
    return networkState;
}

public LiveData<PagedList<Article>> getArticleLiveData() {
    return articleLiveData;
}

活动

public class FeedActivity extends AppCompatActivity {

private FeedListAdapter adapter;
private FeedViewModel feedViewModel;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    /*
     * Step 2: Initialize the ViewModel
     *
     * */
    feedViewModel = new FeedViewModel();

    /*
     * Step 2: Setup the adapter class for the RecyclerView
     *
     * */
    RecyclerView recyclerView = findViewById(R.id.list_feed);
    recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
    adapter = new FeedListAdapter(getApplicationContext());


    /*
     * Step 4: When a new page is available, we call submitList() method
     * of the PagedListAdapter class
     *
     * */
    feedViewModel.getArticleLiveData().observe(this, pagedList -> {
        Log.d("TAG", "onCreate: ");
        adapter.submitList(pagedList);
    });

    /*
     * Step 5: When a new page is available, we call submitList() method
     * of the PagedListAdapter class
     *
     * */
    feedViewModel.getNetworkState().observe(this, networkState -> {
        adapter.setNetworkState(networkState);
    });

    recyclerView.setAdapter(adapter);
}

0 个答案:

没有答案