-

   rss_rss_hh_new

 - e-mail

 

 -

 LiveInternet.ru:
: 17.03.2011
:
:
: 51

:


[ ] Observable Android

, 20 2017 . 15:47 +
Implozia 15:47

Observable Android

, . Observable, android , ( ).

? Observable. , ? , , , .

c Java, . , , :

1) :

public Observable getState(Context context) {
        BigInteger i = ZERO;
        return Observable.create(
                subscriber -> {
                        while (true) subscriber.onNext(i);
                                i = i.add(ONE); 
                }
        );
    }

2) :

public Observable getNetworkState(Context context) {
        BigInteger i = ZERO;
        return Observable.create(
                subscriber -> {
                    Runnable r = () -> {
                        while (!subscriber.isUnsubscribed())
                            while (true) subscriber.onNext(i);
                            i = i.add(ONE); 
                    };
                    new Thread(r).start();
                }
        );
    }

? , , , , , . , . .

, subscribe() , . interrup'.

, . UI Handler.

? . , .

, Observable, , , . :

public class NetworkState {
    /**
     * @param context       ( 
       {@link android.app.Activity})
     * @return {@link Observable}    :
     * 
* true - * * *
* false - * */ public Observable getNetworkState(Context context) { return Observable.create( subscriber -> { Runnable r = () -> { while (!subscriber.isUnsubscribed()) subscriber.onNext(hasConnection(context)); }; new Thread(r).start(); } ); } /** * * @param context * @return true - , false - */ private static boolean hasConnection(final Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo wifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); NetworkInfo mobileInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); return wifiInfo != null && wifiInfo.isConnected() || mobileInfo != null && mobileInfo.isConnected(); } }

, , ( ):

/**
*    ,        TextView,  ,    
**/
private void rxNetworkCheck(){
        new NetworkManager().getNetworkState(this).subscribe(x ->
                handlerNetwork.post(() -> {
                    if(x){
                        buttonNext.setVisibility(View.VISIBLE);
                        textViewNoConnection.setVisibility(View.INVISIBLE);
                    }
                    else{
                        buttonNext.setVisibility(View.INVISIBLE);
                        textViewNoConnection.setVisibility(View.VISIBLE);
                    }
                })
        );
    }

: , , . . , .

, , , , - .

, RxJava .
Original source: habrahabr.ru (comments, light).

https://habrahabr.ru/post/338342/

:  

: [1] []
 

:
: 

: ( )

:

  URL