Observable集合中的筛选列表



我想通过指定的事件过滤Observable集合中的List <Notification>

这是一个改装电话:

@GET("/notifications")
Observable<NotificationCollection> getNotifications(@Query("page") Integer page);

NotificationCollection型号:

class NotificationCollection {
var items: List<Notification>? = null
var pagination: Pagination? = null
}

Notification型号:

class Notification {
var event: String? = null
var id: Long? = null
var data: NotificationData? = null
}

在助手类中,我将Observable返回给interator:

override fun getNotifications(page: Int): Observable<NotificationCollection> {
return service.getNotifications(page)
}

我尝试了几种方法:

override fun getNotifications(page: Int): Observable<NotificationCollection> {
return service.getNotificationsTimeline(page)
.filter { it.items?.get(0)?.event == "STORY"}
}

在这里,我想将谓词应用于所有列表项,而不仅仅是我通过索引定义的列表项。有没有办法制作类似.filter { it.items.event = "STORY"}的东西?

我尝试在这里使用flatMap的另一种方法,这对我来说更有意义,但我不知道如何将我的过滤结果映射到Observable<NotificationCollection>的原始响应类型,而不是像这里那样映射到Observable<Notification>

return service.getNotifications(page)
.flatMap { Observable.fromIterable(it.items) }
.filter {it.event == "STORY"}

最简单的方法是用flatMap在我的presenter类中应用filter函数,但我想推广我的解决方案,因为helper类中的方法在不同的地方被调用。所以我想在这里过滤列表。

那么,有没有办法过滤Observable集合中的列表并返回Observable<NotificationCollection>的原始响应类型?

您应该同时使用"filter"one_answers"any"。

class Test {
init {
val testList = listOf(
TestData("1","1", listOf("1a")),
TestData("2","2", listOf("2b")),
TestData("3","3", listOf("3c")))
val result = testList.filter { item ->
item.c.any { it == "STORY" }
}
}
}
data class TestData(val a: String, val b: String, val c: List<String>)

最新更新