Search code examples
androidsystem.reactivekotlinrx-kotlin

Can't Change Text of ActionMenuItemView with RxKotlin


I'm trying to write an Android app with Kotlin. Now, I want to show a counter in the ActionBar. I added an item called show_timer for that. Each second, it should count up by one:

override fun onWindowFocusChanged(hasFocus: Boolean) {
    val item = findViewById(R.id.show_timer) as ActionMenuItemView
    PublishSubject.interval(1, java.util.concurrent.TimeUnit.SECONDS, Schedulers.newThread())
            .subscribeBy(onNext = {item.text = it.toString()})

    super.onWindowFocusChanged(hasFocus)
}

But somehow this doesn't work. It updates the default text to 0, but after that it does nothing. Does someone know why this doesn't work?

Thank you in advance,

Niklas


Solution

  • In order for the text to update, it needs to be updated on the main thread (not the Schedulers.newThread() one)

    Adding:

    .observeOn(AndroidSchedulers.mainThread())
    

    Should fix things, and get the label to update