Rxjava过滤List中的重复项
Rxjava Filtering the duplicate item in List
我在我的 App.Here 的设置中使用 RxJava 和 Retrofit app.When 应用程序启动应用程序发出两个请求,一个到数据库,另一个到网络 Api(使用 Retrofit)并且都请求 return a Observable<List<Article>>
。所以我所做的基本上是合并两个 Observable。现在的问题有时是数据库中已经存在的网络 return 文章。那么如何从列表中过滤掉重复项。这是我的代码。
return Observable.merge(dataSource.getArticles(source), remoteSource.getArticles(source))
.distinct();
所以我尝试了 distinct 运算符,但它没有过滤文章 out.Here,输出看起来像 db.
Article1
Article2
Article3
Article4
来自网络的输出
Article7
Articke8
Article3
Article4
我要的是文章的不同列表
那是因为他们返回了不同的 列表。所以 distinct
方法将它们识别为不同的项目
如果您想先发出数据库项,然后再添加服务器项...这可能有点复杂,但不会太多 ;)
Observable<List<Article>> databaseArticles = ...
Observable<List<Article>> serverArticles = ...
Observable<List<Article>> allArticles =
Observable.combineLatest(
databaseArticles,
serverArticles
.startWith(emptyList()), // so it doesn't have to wait until server response
(dbItems, sItems) => {
// Combine both lists without duplicates
// e.g.
Set<Article> all = new HashSet<>();
Collections.addAll(all, dbItems);
Collections.addAll(all, sItems);
return new ArrayList<>(all);
});
假设您的 Article
具有正确的 equals
实施,
您可以将它们收集成一组:
dataSource.getArticles(source)
.mergeWith(remoteSource.getArticles(source))
.collect(HashSet::new, (set, list) -> set.addAll(list))
或者您可以展开每个列表并应用 distinct
然后是 toList
:
dataSource.getArticles(source)
.mergeWith(remoteSource.getArticles(source))
.flatMapIterable(v -> v)
.distinct()
.toList()
我在我的 App.Here 的设置中使用 RxJava 和 Retrofit app.When 应用程序启动应用程序发出两个请求,一个到数据库,另一个到网络 Api(使用 Retrofit)并且都请求 return a Observable<List<Article>>
。所以我所做的基本上是合并两个 Observable。现在的问题有时是数据库中已经存在的网络 return 文章。那么如何从列表中过滤掉重复项。这是我的代码。
return Observable.merge(dataSource.getArticles(source), remoteSource.getArticles(source))
.distinct();
所以我尝试了 distinct 运算符,但它没有过滤文章 out.Here,输出看起来像 db.
Article1
Article2
Article3
Article4
来自网络的输出
Article7
Articke8
Article3
Article4
我要的是文章的不同列表
那是因为他们返回了不同的 列表。所以 distinct
方法将它们识别为不同的项目
如果您想先发出数据库项,然后再添加服务器项...这可能有点复杂,但不会太多 ;)
Observable<List<Article>> databaseArticles = ...
Observable<List<Article>> serverArticles = ...
Observable<List<Article>> allArticles =
Observable.combineLatest(
databaseArticles,
serverArticles
.startWith(emptyList()), // so it doesn't have to wait until server response
(dbItems, sItems) => {
// Combine both lists without duplicates
// e.g.
Set<Article> all = new HashSet<>();
Collections.addAll(all, dbItems);
Collections.addAll(all, sItems);
return new ArrayList<>(all);
});
假设您的 Article
具有正确的 equals
实施,
您可以将它们收集成一组:
dataSource.getArticles(source)
.mergeWith(remoteSource.getArticles(source))
.collect(HashSet::new, (set, list) -> set.addAll(list))
或者您可以展开每个列表并应用 distinct
然后是 toList
:
dataSource.getArticles(source)
.mergeWith(remoteSource.getArticles(source))
.flatMapIterable(v -> v)
.distinct()
.toList()