GuessWho
GuessWho

Reputation: 672

android Rx function in new thread

The task is trivial - I need to start some function in new thread and show the result in UI.

Here is my code

class FragmentKKMInfo {

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        getKKMInfo().subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ info ->
                    Log.i("RX", "LOG3")
                    //doUIStaff()
                }, { error ->

                    Toast.makeText(context, error.message, Toast.LENGTH_LONG).show()

                })

        Log.i("RX", "LOG1")
    }

    private fun getKKMInfo(): Observable<KKMInfo> {

        Thread.sleep(3000)
        Log.i("RX", "LOG2")

        //doSomeStaff()

        return Observable.just(KKMInfo(
                date,
                shift_model_name,
                shift_serial_number,
                shift_state_string
        ))
    }

}

I'm expected to get LOG1, LOG2, LOG3. But Fragment does't show until the whole code will be complete and my logs are LOG2, LOG1, LOG3.

What's the right way to do this?

Upvotes: 0

Views: 200

Answers (1)

Dmitry
Dmitry

Reputation: 2526

That is because Thread.sleep(3000) is being executed on the Main Thread. You are creating your rx stream AFTER Thread.sleep(3000) was executed. You can change your getKKMInfo method to the following to get the desired result:

private fun getKKMInfo(): Observable<KKMInfo> {
        return Observable.fromCallable {
            Thread.sleep(3000)
            Log.i("RX", "LOG2")

            //doSomeStaff()

            return@fromCallable KKMInfo(
                    date,
                    shift_model_name,
                    shift_serial_number,
                    shift_state_string)
        }
    }

Upvotes: 4

Related Questions