如何过滤Livedata或Rxjava flowable

时间:2019-10-05 19:32:18

标签: android rx-java rx-java2 android-livedata

使用改造,我从服务器获取Flowable数据,然后在viewmodel中将Flowable转换为Livedata,最后观察活动中的LiveData。内部活动中,我将Livedata用于我的recyclerView。

但是我需要过滤某些条件的数据,并将过滤后的数据列表作为LiveData获取。我如何以及在哪里做?我可以过滤Livedata吗?

我正在做的步骤是:

  1. 在我的 MainApi类中:使用翻新方式调用网络服务,并返回Flowable结果
public interface MainApi {
    @GET("xx")
    Flowable<List<User>> getUsers();
}
  1. 在我的存储库课程中:
public class MainRepository {
    public Flowable<List<User>> fetchUsersFromServer() {   
        Flowable<List<User>> returnedData = mainApi
            .getUsers()
            .subscribeOn(Schedulers.io());

        return returnedData;
    }   
}
  1. 在我的 viewModel类中:可从存储库中流动并转换为LiveData
public class MainViewModel extends ViewModel {
    MediatorLiveData<List<User>> liveUsers = new MediatorLiveData();

    public void getUsersFromServer() {

    final LiveData<List<User>> source = LiveDataReactiveStreams.fromPublisher( mainRepository.fetchUsersFromServer());

    liveUsers.addSource(source, new Observer<List<User>>() {
          @Override
          public void onChanged(List<User> users) {
              liveUsers.setValue(users);
              liveUsers.removeSource(source);
          }
        });     
    }
}   
  1. 最后观察活动中的LiveData,并在Recyclerview中显示数据

1 个答案:

答案 0 :(得分:0)

在将filteredposts = posts.where((snapshot) => snapshot.typeX == true).toList(); 返回的可观察对象中转换为LiveData之前,可以对其进行过滤。

mainRepository.fetchUsersFromServer()