【问题标题】:Observable subscribe not getting called on same valueObservable subscribe 没有被调用相同的值
【发布时间】:2019-03-29 17:43:21
【问题描述】:

我有一个 BehaviourSubject 作为我的 Retrofit 方法的回调。

private val loadCompleted = BehaviourSubject.create<List<String>>()

在我的改造 OnResponse/onFailure 中,我调用了

loadCompleted.onNext(myList) //inside retrofit onResponse and 
loadCompleted.onError("Error") // inside retrofit onFailure

我订阅了一个返回 loadCompleted 的函数。

fun loadingCompleted() : Observable<List<String>>{return loadCompleted}

然后我订阅 loadingCompleted 为

loadingCompleted.subscribe{list -> 
     //only called once
     anotherfun(list)
}

第一次调用我的 Retrofit 函数时,我可以调用我的订阅,但随后对同一函数的调用不会触发订阅。我假设调用通常返回相同的值,因为它只是一次刷新并且数据可能没有改变。但是,我仍然需要调用订阅,以便做出相应的反应。我已经尝试过 BS 和 ReplaySubject 但结果是一样的。如何使用 observable 来确保在调用 onNext(x)/onComplete(x) 时始终调用订阅,即使 x 可能没有改变?

【问题讨论】:

    标签: android kotlin rx-java2 behaviorsubject


    【解决方案1】:

    您可能正在使用onComplete/onError 完成您的BehaviorSubject 流。如果您不想这样做,请将 x/error 包装到某种密封类并具有 SuccessFailure 子类的 Result 中。然后总是使用subject.onNext() 来发射。

    sealed class Result<T> {
        class Success<T>(val t: T) : Result<T>()
        class Failure<T>(val e: Throwable) : Result<T>()
    }
    
    class Test {
        val subject: BehaviorSubject<Result<List<String>>> = BehaviorSubject.create()
    
        fun call() {
            subject.onNext(Result.Success(listOf("example")))
            subject.onNext(Result.Failure(RuntimeException("error")))
    
            subject.subscribe{result->
                when(result){
                    is Result.Success -> print(result.t)
                    is Result.Failure -> print(result.e.message)
                }
            }
        }
    
    }
    

    【讨论】:

    • 感谢您的快速回复。你介意给我一个例子来说明我是怎么做到的吗?我是 Rx 编程的新手,并试图围绕它进行思考。谢谢
    猜你喜欢
    • 2021-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-06
    • 1970-01-01
    • 1970-01-01
    • 2018-01-12
    相关资源
    最近更新 更多