1.基础
RxKotlin基于RxJava (Reactive X文档链接),利用Kotlin语言特性做了一些拓展
2.集成方式
以gradle为例,集成当前版本:
implementation 'io.reactivex.rxjava2:rxkotlin:2.2.0`
集成最新版本:
implementation 'io.reactivex.rxjava2:rxkotlin:latest.integration'
3.接口
1.toObservable接口
将array转为Observable
val list = listOf("Alpha", "Beta", "Gamma", "Delta", "Epsilon")
list.toObservable()
.filter { it.length >=5 }
.subscribe(
{
println("emitting $it")
}
)
//print:
//emitting Alpha
//emitting Gamma
//emitting Delta
//emitting Epsilon
复制代码
2.flatMapSequence
Flat maps each T
emission to a Sequence<R>
val list = listOf("Alpha", "Beta")
list.toObservable()
.flatMapSequence<String, Char> {
Sequence {
it.iterator()
}
}
.subscribe{
println(it)
}
//print:
//A
//l
//p
//h
//a
//B
//e
//t
//a
复制代码
3.toMap
Collects Pair<A,B>
emissions into a Map<A,B>
原文档写作Map<A,B>
但实际应当是Map<C, Pair<A,B>>
, C是toMap接收的lamda返回的类型
val pairList = listOf(Pair("123", "123"),
Pair("456", " 456"))
pairList.toObservable()
.toMap {
//returns the key of map
"${it.first} and ${it.second}"
}
.subscribe({
println(it)
//prints:
//{123 and 123=(123, 123), 456 and 456=(456, 456)}
},{
//error handling, ignore
})
复制代码
4.toMultimap
Collects Pair<A,B>
emissions into a Map<A,List<B>>
,实际应为Map<C, Pair<A, B>>
, C为toMultimap返回的类型
val pairList = listOf(Pair("123", "123"), Pair("123", "456"))
pairList.toObservable()
.toMultimap {
//key of the map returned
it.first
}
.subscribe({//it:(Mutable)Map<String!, (Mutable)Collection<Pair<String, String>!>!>!
//print:
//{123=[(123, 123), (123, 456)]}
println(it)
},{
//ignore error
})
复制代码
5.mergeAll
Merges all Observables emitted from an Observable,接收类型Observable<Observable>
, 底层调用RxJava的flatMap
val l1 = listOf("1", "2", "3", "4", "5", "6")
val l2 = listOf("4", "5", "6")
val l3 = listOf(l1.toObservable(), l2.toObservable())
l3.toObservable()
.mergeAll()
.subscribe {
//print 1 2 3 4 5 6 4 5 6
//emissions from two source observable are merged
println(it)
}
复制代码
6.concatAll
Cocnatenates all Observables emitted from an Observable,与mergeAll类似,但底层调用RxJava concatMap
val l1 = listOf("1", "2", "3")
val l2 = listOf("4", "5", "6")
val l3 = listOf(l1.toObservable(), l2.toObservable())
l3.toObservable()
.concatAll()
.subscribe {
//print: 1 2 3 4 5 6
println(it)
}
复制代码
7.switchLatest
Emits from the last emitted Observable
val l1 = listOf("1", "2", "3")
val l2 = listOf("4", "5", "6")
val l3 = listOf("7", "8", "9")
val ll = listOf(l1.toObservable(),
l2.toObservable(),
l3.toObservable())
ll.toObservable()
.switchLatest()
.subscribe({
//print: 1 2 3 4 5 6 7 8 9
println(it)
})
复制代码
8.cast
Casts all emissions to the reified type,如果参数类型与目标类型不一致,会抛出异常OnErrorNotImplementedException
val l1 : List<Any> = listOf("1", "2", "3")
l1.toObservable()
.cast(String::class.java)
.subscribe({
//print: 1 2 3
println(it)
})
复制代码
9.ofType
Filters all emissions to only the reified type
val list : List<Any> = listOf("abc", 612, "def")
list.toObservable()
.ofType(String::class.java)
.subscribe({
//print: abc def
println(it)
})
复制代码