可观察的订阅没有被调用相同的值

Observable subscribe not getting called on same value

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

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

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

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

我订阅了 return 加载完成的功能。

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

然后我将 loadingCompleted 订阅为

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

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

您可能正在 onComplete/onError 结束您的 BehaviorSubject 直播。如果您不想这样做,请将 x/error 包装到某种密封 class 并且具有 SuccessFailure subclass 的结果中。然后总是使用 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)
            }
        }
    }

}