android.os.NetworkOnMainThreadException using rxjava on android

后端 未结 4 1636
臣服心动
臣服心动 2021-01-17 12:11

i\'m having trouble implementing rxJava in order to check if there is internet connection on android i\'m doing it like this:

on my launcher activity i have this in

4条回答
  •  执念已碎
    2021-01-17 12:48

    this is my retrieve data from DataBase by RXAndroid code:

        Observable.create(new Observable.OnSubscribe>() {
            @Override
            public void call(Subscriber> subscriber) {
    
                String jsonIn;
                jsonIn =retrieveDataFromDB();
                Gson gson = new Gson();
                Type listType = new TypeToken>() {
    
                }.getType();   
                eventJoinList = gson.fromJson(jsonIn, listType);
                Log.d("RX",jsonIn);
                subscriber.onNext(eventJoinList);
            }
        })
    
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Action1>() {
            @Override
            public void call(List eventJoinList) {
                Log.d("RX", ".subscribe");
           recyclerView.setAdapter(new EventJoinAdapter(eventJoinList));
            }
        });
    

    I think the just operator will emit data immediately, so it's is not useful to retrieve data from a database via network. It is very easy to use, but it can only be used for data that's already in the ram of the device.

    I also had that problem, like @Baniares had, but after I use the create operator, all the problem gone...

    From the RXJava documentation:

    static Observable create(Observable.OnSubscribe f)

    Returns an Observable that will execute the specified function when a Subscriber subscribes to it.

    Using the create operator can establish the standard process:

    1 .subscribe(...) Subscriber(the sub class of class Observer) start the connection to Observable.

    2 .subscribeOn(Schedulers.io()) collect a backGround Thread from the RX-ThreadPool

    3 .create(...) retrieve data from server...during some netWork..etc

    4 .observeOn(AndroidSchedulers.mainThread()) this means data will be set by the UI-Thread

    5 Once we get the data , we can set the data in the onNext( ) method in the .subscribe( ) , the data will be set on the UI by UI-Thread since we make UI-thread do the work on the .observerOn(AndroidSchedulers.mainThread())

    And note that if you use .create( ) operator,you must finished your observable in the .create( ) , others operator such like map,flatMap will not be executed after the .create( ) operator.

    A very important concept we must need to know before start to use RXJava/RXAndroid. RX is a callback-based library, you tell RX what it should to do in what condition, it invoke your pass-in function(or in JAVA I may should to call them anonymous inner class... ) to achieve what you want.

提交回复
热议问题