我的
MainRepository
是从API获取数据并插入数据库,然后在UI上显示的内容。
override fun fetchAll() {
Observable.fromCallable { local.fetchPosts() }
.doOnNext {
remote.fetchPosts().concatMap { posts ->
local.insert(*posts.toTypedArray())
Observable.just(posts)
}
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ outcome.success(it) },
{ error: Throwable -> outcome.failed(error) }
).addTo(compositeDisposable)
}
这个
outcome
变量是
PublishObject
类型
Response
,即
Loading
,
Success
Failure
.
override val outcome = PublishSubject.create<Response<List<Post>>>()
[...]
sealed class Response<T> {
companion object {
fun <T> loading(loading: Boolean): Response<T> = Progress(loading)
fun <T> success(data: T): Response<T> = Success(data)
fun <T> failure(e: Throwable): Response<T> = Failure(e)
}
data class Progress<T>(var loading: Boolean) : Response<T>()
data class Success<T>(var data: T) : Response<T>()
data class Failure<T>(var e: Throwable) : Response<T>()
}
它执行一个方法
local.fetchPosts()
,这是一个负责访问DAO函数的函数。
fun fetchPosts() = database.postDao().fetchAll()
[...]
@Query("SELECT * FROM posts ORDER BY createdAt DESC")
fun fetchAll(): List<Post>
addTo
是
Disposable
:
fun Disposable.addTo(compositeDisposable: CompositeDisposable) {
compositeDisposable.add(this)
}
我试过用
concatMap
就在那之后
Observable.fromCallable
,但在
doOnNext