參考:
tbruyelle / RxPermissions : 無界面fragment
collectInto
/**
* 將集合中元素以逗號連接並返回
* public final <U> Single<U> collectInto(
* final U initialValue,
* BiConsumer<? super U, ? super T> collector
* )
*/
private fun collectIntoName(list: MutableList<String>): String? {
return Observable.fromIterable(list)
.filter {
it.isNotEmpty()
}
.collectInto(StringBuilder(), { stringBuilder, item ->
if (stringBuilder.isEmpty()) {
stringBuilder.append(item)
} else {
stringBuilder.append(", ").append(item)
}
})
.blockingGet()
.toString()
}
collect
/**
* 將集合中元素以逗號連接並返回
* public final <U> Single<U> collect(
* Callable<? extends U> initialValueSupplier,
* BiConsumer<? super U, ? super T> collector
* )
*/
private fun collectName(list: MutableList<String>): String? {
return Observable.fromIterable(list)
.filter {
it.isNotEmpty()
}
.collect({ StringBuilder() }) { stringBuilder, item ->
if (stringBuilder.isEmpty()) {
stringBuilder.append(item)
} else {
stringBuilder.append(", ").append(item)
}
}
.blockingGet()
.toString()
}
all
/**
* 集合中是否都非空
* public final Single<Boolean> all(Predicate<? super T> predicate) {
*/
private fun hasNoEmptyItem(list: List<String>): Boolean? {
return Observable.fromIterable(list)
.all {
it.isNotEmpty()
}.blockingGet()
}
any
/**
* 集合中是否包含空元素
* public final Single<Boolean> any(Predicate<? super T> predicate) {
*/
private fun hasEmptyItem(list: List<String>): Boolean? {
return Observable.fromIterable(list)
.any {
it.isEmpty()
}
.blockingGet()
}
測試
private val lists1: MutableList<String> = mutableListOf(
"1",
"10",
"18",
"",
"101",
"51"
)
private val lists2: MutableList<String> = mutableListOf(
"1",
"10",
"18",
"101",
"51"
)
println("1===========================" + collectIntoName(lists1))
println("1===========================" + collectName(lists1))
println("2===========================" + hasNoEmptyItem(lists1))
println("3===========================" + hasEmptyItem(lists1))
println("=========================================================")
println("1===========================" + collectIntoName(lists2))
println("1===========================" + collectName(lists2))
println("2===========================" + hasNoEmptyItem(lists2))
println("3===========================" + hasEmptyItem(lists2))
//1===========================1, 10, 18, 101, 51
//1===========================1, 10, 18, 101, 51
//2===========================false
//3===========================true
//=========================================================
//1===========================1, 10, 18, 101, 51
//1===========================1, 10, 18, 101, 51
//2===========================true
//3===========================false