gpt4 book ai didi

android - Kotlin:如何继承RxJava Subscriber

转载 作者:行者123 更新时间:2023-11-30 01:31:44 27 4
gpt4 key购买 nike

我希望我的 NewsListSubscriber 继承自使用通用类型的 RxJava 订阅者,但在调用 UseCase 执行方法时出现“类型不匹配”错误。我多次阅读 Kotlin 文档中的泛型页面,但找不到解决方案。

这是我的用例:

abstract class UseCase(private val threadExecutor: IThreadExecutor,
private val postExecutionThread: IPostExecutionThread) {

private var subscription = Subscriptions.empty()

fun execute(UseCaseSubscriber: rx.Subscriber<Any>) {
subscription = buildUseCaseObservable()
.subscribeOn(Schedulers.from(threadExecutor))
.observeOn(postExecutionThread.getScheduler())
.subscribe(UseCaseSubscriber)
}

protected abstract fun buildUseCaseObservable(): Observable<out Any>

fun unsubscribe() {
if (!subscription.isUnsubscribed) {
subscription.unsubscribe()
}
}
}

我是这样调用它的:

override fun loadNewsList() {
getNewsListInteractor.execute(NewsListSubscriber())
}

private inner class NewsListSubscriber : rx.Subscriber<List<NewsModel>>() {
override fun onCompleted() {// TODO}

override fun onError(e: Throwable) {// TODO}

override fun onNext(t: List<NewsModel>) {// TODO}
}

错误是

"Type mismatch. Required: rx.Subscriber. Found: Presenters.NewsListPresenter.NewsListSubscriber"

在“执行(NewsListSubscriber())”行中。我尝试使用“in”和“out”关键字,但我仍然遇到同样的错误。

最佳答案

其实有更好的方法来解决这个问题。我遇到了同样的问题,并且在每个派生订阅者类中进行类型转换不是一种选择。

只需使用通用类型参数更新抽象 UseCase 类即可。

abstract class UseCase<T>(private val threadExecutor: IThreadExecutor,
private val postExecutionThread: IPostExecutionThread) {

private var subscription = Subscriptions.empty()

fun execute(UseCaseSubscriber: rx.Subscriber<T>) {
subscription = buildUseCaseObservable()
.subscribeOn(Schedulers.from(threadExecutor))
.observeOn(postExecutionThread.getScheduler())
.subscribe(UseCaseSubscriber)
}

protected abstract fun buildUseCaseObservable(): Observable<T>

fun unsubscribe() {
if (!subscription.isUnsubscribed) {
subscription.unsubscribe()
}
}
}

当您声明您的派生用例类时,在调用父类(super class)时使用您的具体类型作为泛型参数。

class ConcreteUseCase(val threadExecutor: IThreadExecutor,
val postExecutionThread: IPostExecutionThread)
: UseCase<ConcreteType>(threadExecutor, postExecutionThread)

这样,您就可以在execute 调用中使用类型化订阅者。

getNewsListInteractor.execute(NewsListSubscriber())

...

private inner class NewsListSubscriber : rx.Subscriber<List<NewsModel() {
override fun onCompleted() {// TODO}

override fun onError(e: Throwable) {// TODO}

override fun onNext(t: List<NewsModel>) {// TODO}
}

关于android - Kotlin:如何继承RxJava Subscriber,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35661625/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com