0

I want to get MutableLiveData<List<Country>>() object from Observable<List<Country>>, but I'm not able to find a way.

I'm using implementation below, but it's not working. Is there any other way to achieve it, or am I doing something wrong with my current implementation?

dataManagerAnonymous.countries.toList().blockingGet().single()

The above code shows NetworkOnMainThreadException and crashes the Application.

Tamir Abutbul
  • 7,301
  • 7
  • 25
  • 53
miPlodder
  • 795
  • 8
  • 18
  • 1
    Possible duplicate of [How do I fix android.os.NetworkOnMainThreadException?](https://stackoverflow.com/questions/6343166/how-do-i-fix-android-os-networkonmainthreadexception) – Nongthonbam Tonthoi Jul 07 '19 at 10:03
  • Please write what you want clearly. Firstly, your title question and description question are not same. In your title you need List while in your description you need MutableLiveData>. Also you are asking two question with a single post. Your first question is related to type conversion and latter is about threading which is totally different subject. That being said, I believe there are so many questions and answers regarding both questions. It is recommended you research before you ask question. Let's keep the community well organized – musooff Jul 11 '19 at 01:29

1 Answers1

0
dataManagerAnonymous
    .countires
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe { result ->
        // result is List<Country>
    }

dataManagerAnonymous.countires probably perform network request, which should be done on background thread in order to prevent UI thread from blocking. subscribeOn(Schedulers.io()) invokes your request on background thread. observeOn(AndroidSchedulers.mainThread()) lets you to use result of this call on UI thread. Subscribe block will be called when your request had been completed successfully and result data is ready to process.

Asad Ali Choudhry
  • 4,985
  • 4
  • 31
  • 36
BochenChleba
  • 238
  • 1
  • 7
  • Why is `blockingGet()` showing NetworkError, in some places it's not showing, whereas some places like mentioned in Question, its showing ? – miPlodder Jul 07 '19 at 10:57
  • 1
    @miPlodder blockingGet() blocks current thread until result of method is available. If you call blockingGet() on main thread (user interface thread) it will throw an error. You shouldn't do this, because until the result of network call arrives, your application is frozen (e.g. clicking a button will not be handled). However If you call blockingGet() on background thread you will not get an error. Blocking background thread is not making your app unresponsive. – BochenChleba Jul 07 '19 at 16:52