MVVM RXAndroid无法在后台线程上调用setValue

时间:2019-01-01 23:19:48

标签: android retrofit2 rx-android

在我的应用程序中,我请求json填充recyclerview,它在首次初始化kotlin viewmodel时总是成功,但是当我想在timer.schedule方法中再次请求时,它将转到一次性订阅中的onError方法,这是在xml视图中绑定的Edittext的onTextChange:

fun onSearchTextChanged(text: CharSequence) {
    if (text.isNotEmpty()) {
        if (myTimer != null) {
            myTimer!!.cancel()
        }

        myTimer = Timer()
        myTimer!!.schedule(object : TimerTask() {
            override fun run() {
                loadMovies(text.toString(), 1)
            }

        }, 1000)
    } else {
        if (myTimer != null) {
            myTimer!!.cancel()
        }
    }
}

这是我的请求方法:

fun loadMovies(searchText: String, pageNumber: Int) {
    subscription = searchApi.getSearch(API_KEY, searchText, pageNumber)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .doOnSubscribe { onRetrieveMoviesListStart() }
        .doOnTerminate { onRetrieveMoviesListFinish() }
        .subscribe(
            { result -> onRetrieveMoviesListSuccess(result) },
            { err -> onRetrieveMoviesListError(err) })
}

private fun onRetrieveMoviesListStart() {
    loadingVisibility.value = View.VISIBLE
    Timber.d("started")
}

private fun onRetrieveMoviesListFinish() {
    loadingVisibility.value = View.GONE
    Timber.d("finished")
}

private fun onRetrieveMoviesListSuccess(search: Search) {
    Timber.d(search.toString())
    movieListAdapter.updateMoviesList(search.Search)
    movieEvent.value = MovieEvent.ANIMATE_RECYCLER
}

private fun onRetrieveMoviesListError(err: Throwable) {
    Timber.e(err)
}

这是viewModel类声明:

@Inject
lateinit var searchApi: SearchApi

val movieListAdapter: MovieListAdapter = MovieListAdapter()
private var myTimer: Timer? = null

private val movieEvent = SingleLiveEvent<MovieEvent>()
private lateinit var subscription: Disposable
val loadingVisibility: MutableLiveData<Int> = MutableLiveData()

init {
    loadMovies("someText", 1)
}

我该怎么办?

1 个答案:

答案 0 :(得分:3)

您在ViewModel初始化中对loadMovies的初始调用来自主/ UI线程。 timertask对loadMovies的调用来自后台线程。现在我对rx没有太多经验,但问题似乎仍然与livedata有关。

您正在观察主线程,这对于成功方法和错误方法都很好。您的问题似乎是从backround线程调用的onRetrieveMoviesListStart()和onRetrieveMoviesListFinish()。

只能从主线程中调用实时数据的值的设置方法,要从后台线程中设置值,您需要调用 postValue

更改这样的两个方法/函数应该可以解决问题:

private fun onRetrieveMoviesListStart() { 
    loadingVisibility.postValue(View.VISIBLE)
    Timber.d("started")
} 
private fun onRetrieveMoviesListFinish() {
    loadingVisibility.postValue(View.GONE)
    Timber.d("finished")
}