Search in sources :

Example 1 with NonNull

use of io.reactivex.annotations.NonNull in project simple-stack by Zhuinden.

the class Chat method getMessages.

public Observable<Message> getMessages() {
    return Observable.create(new ObservableOnSubscribe<Message>() {

        @Override
        public void subscribe(@NonNull ObservableEmitter<Message> emitter) throws Exception {
            final Random random = new Random();
            while (true) {
                if (random.nextInt(PROBABILITY) == 0) {
                    try {
                        User from = users.get(random.nextInt(users.size()));
                        Response<Quotes> response = chats.service.getQuote().execute();
                        Quotes quotes = response.body();
                        if (quotes == null) {
                            throw new Exception("Could not download quotes [" + response.errorBody().string() + "] ");
                        }
                        Quote quote = quotes.getContents().getQuotes().get(0);
                        Message next = new Message(from, quote.getQuote());
                        messages.add(next);
                        if (!emitter.isDisposed()) {
                            emitter.onNext(next);
                        }
                    } catch (Exception e) {
                        if (!emitter.isDisposed()) {
                            emitter.onError(e);
                            break;
                        }
                    }
                }
                try {
                    // Hijacking the thread like this is sleazey, but you get the idea.
                    Thread.sleep(SLEEP_MILLIS);
                } catch (InterruptedException e) {
                    if (!emitter.isDisposed()) {
                        emitter.onError(e);
                    }
                    break;
                }
            }
        }
    }).startWith(//
    messages).subscribeOn(//
    Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
}
Also used : Quote(com.example.mortar.model.quotes.Quote) ObservableOnSubscribe(io.reactivex.ObservableOnSubscribe) Random(java.util.Random) NonNull(io.reactivex.annotations.NonNull) Quotes(com.example.mortar.model.quotes.Quotes) ObservableEmitter(io.reactivex.ObservableEmitter)

Example 2 with NonNull

use of io.reactivex.annotations.NonNull in project GitTest by xiaoxige.

the class MainActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    testView = (TestView) findViewById(R.id.testView);
    testView.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            MainActivityPermissionsDispatcher.showCameraWithPermissionCheck(MainActivity.this);
        }
    });
    try {
        ApplicationInfo appInfo = getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
        String appMV = appInfo.metaData.getString("MTA_CHANNEL");
        Toast.makeText(MainActivity.this, "appMV = " + appMV, Toast.LENGTH_SHORT).show();
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    simpleDraweeView = (SimpleDraweeView) findViewById(R.id.simpleDraweeView);
    testView.setProgress(100, false);
    new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {
            testView.setProgress(3, true);
        }
    }, 2000);
    GenericDraweeHierarchy hierarchy = simpleDraweeView.getHierarchy();
    RoundingParams roundingParams = new RoundingParams();
    roundingParams.setBorder(Color.RED, 10);
    roundingParams.setRoundAsCircle(true);
    hierarchy.setRoundingParams(roundingParams);
    simpleDraweeView.setHierarchy(hierarchy);
    ControllerListener listener = new BaseControllerListener() {

        @Override
        public void onFinalImageSet(String id, @Nullable Object imageInfo, @Nullable Animatable animatable) {
            super.onFinalImageSet(id, imageInfo, animatable);
        }
    };
    DraweeController controller = Fresco.newDraweeControllerBuilder().setUri(new Uri.Builder().scheme(UriUtil.LOCAL_RESOURCE_SCHEME).path(String.valueOf(R.mipmap.ic_launcher)).build()).setOldController(simpleDraweeView.getController()).setControllerListener(listener).build();
    simpleDraweeView.setController(controller);
    /**
     * 网络相关(retrofit+rxjava+rxlife+stetho)
     */
    OkHttpClient client = new OkHttpClient.Builder().connectTimeout(5000, TimeUnit.SECONDS).readTimeout(5000, TimeUnit.SECONDS).writeTimeout(5000, TimeUnit.SECONDS).addNetworkInterceptor(new Interceptor() {

        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Headers headers = request.headers();
            Headers build = headers.newBuilder().add("version", "1.0").add("token", "xiaoxige").build();
            request = request.newBuilder().headers(build).build();
            Log.e("TAG", "url = " + request.url().uri().toString());
            String method = request.method();
            if (method.equals("GET") || method.equals("DELETE")) {
                HttpUrl url = request.url();
                HttpUrl httpUrl = url.newBuilder().addQueryParameter("xiaoxige", "one").addQueryParameter("zhuxiaoan", "two").build();
                request = request.newBuilder().url(httpUrl).build();
            } else {
                RequestBody body = request.body();
                if (body != null) {
                    Buffer buffer = new Buffer();
                    body.writeTo(buffer);
                    String readUtf8 = buffer.readUtf8();
                    // 可能需要对body进行加密
                    // TODO: 2017/11/3
                    RequestBody requestBody = RequestBody.create(body.contentType(), readUtf8);
                    request = request.newBuilder().method(method, requestBody).build();
                }
            }
            return chain.proceed(request);
        }
    }).addNetworkInterceptor(new StethoInterceptor()).build();
    Retrofit retrofit = new Retrofit.Builder().baseUrl("http://www.baidu.com").addConverterFactory(ScalarsConverterFactory.create()).addConverterFactory(GsonConverterFactory.create()).client(client).build();
    final NetApi api = retrofit.create(NetApi.class);
    Flowable flowable = Flowable.create(new FlowableOnSubscribe<String>() {

        @Override
        public void subscribe(@NonNull FlowableEmitter<String> flowableEmitter) throws Exception {
            String response = MainActivity.execute(api.getBaiduWeb());
            if (TextUtils.isEmpty(response)) {
                flowableEmitter.onError(new Exception());
                return;
            }
            flowableEmitter.onNext(response);
            flowableEmitter.onComplete();
        }
    }, BackpressureStrategy.LATEST).compose(bindUntilEvent(ActivityEvent.DESTROY)).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io());
    flowable.subscribe(new XXGSubscriber<String>() {

        @Override
        public void xxgNext(String o) {
            super.xxgNext(o);
            Log.e("TAG", "o = " + o);
        }

        @Override
        public void xxgError(Throwable t) {
            super.xxgError(t);
            Log.e("TAG", "t = " + t.getMessage());
        }

        @Override
        public void xxgComplete() {
            super.xxgComplete();
            Log.e("TAG", "Complete");
        }
    });
}
Also used : OkHttpClient(okhttp3.OkHttpClient) GenericDraweeHierarchy(com.facebook.drawee.generic.GenericDraweeHierarchy) DraweeController(com.facebook.drawee.interfaces.DraweeController) Headers(okhttp3.Headers) ApplicationInfo(android.content.pm.ApplicationInfo) Uri(android.net.Uri) PackageManager(android.content.pm.PackageManager) BaseControllerListener(com.facebook.drawee.controller.BaseControllerListener) NonNull(io.reactivex.annotations.NonNull) FlowableEmitter(io.reactivex.FlowableEmitter) Interceptor(okhttp3.Interceptor) StethoInterceptor(com.facebook.stetho.okhttp3.StethoInterceptor) RoundingParams(com.facebook.drawee.generic.RoundingParams) RequestBody(okhttp3.RequestBody) Buffer(okio.Buffer) FlowableOnSubscribe(io.reactivex.FlowableOnSubscribe) Request(okhttp3.Request) Handler(android.os.Handler) ControllerListener(com.facebook.drawee.controller.ControllerListener) BaseControllerListener(com.facebook.drawee.controller.BaseControllerListener) IOException(java.io.IOException) SimpleDraweeView(com.facebook.drawee.view.SimpleDraweeView) View(android.view.View) HttpUrl(okhttp3.HttpUrl) IOException(java.io.IOException) Response(retrofit2.Response) Retrofit(retrofit2.Retrofit) Animatable(android.graphics.drawable.Animatable) StethoInterceptor(com.facebook.stetho.okhttp3.StethoInterceptor) Nullable(javax.annotation.Nullable) Flowable(io.reactivex.Flowable)

Example 3 with NonNull

use of io.reactivex.annotations.NonNull in project Varis-Android by dkhmelenko.

the class BuildsDetailsPresenter method restartBuild.

/**
     * Restarts build process
     */
public void restartBuild() {
    RequestBody emptyBody = RequestBody.create(MediaType.parse("application/json"), "");
    Disposable subscription = mTravisRestClient.getApiService().restartBuild(mBuildId, emptyBody).onErrorReturn(throwable -> new Object()).flatMap(new Function<Object, SingleSource<BuildDetails>>() {

        @Override
        public SingleSource<BuildDetails> apply(@NonNull Object o) throws Exception {
            return mTravisRestClient.getApiService().getBuild(mRepoSlug, mBuildId);
        }
    }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe((buildDetails, throwable) -> {
        if (throwable == null) {
            handleBuildDetails(buildDetails);
        } else {
            handleLoadingFailed(throwable);
        }
    });
    mSubscriptions.add(subscription);
}
Also used : CompositeDisposable(io.reactivex.disposables.CompositeDisposable) Disposable(io.reactivex.disposables.Disposable) Function(io.reactivex.functions.Function) BuildDetails(com.khmelenko.lab.varis.network.response.BuildDetails) NonNull(io.reactivex.annotations.NonNull) RequestBody(okhttp3.RequestBody)

Example 4 with NonNull

use of io.reactivex.annotations.NonNull in project Varis-Android by dkhmelenko.

the class BuildsDetailsPresenter method startLoadingLog.

/**
     * Starts loading log file
     *
     * @param jobId Job ID
     */
public void startLoadingLog(long jobId) {
    mJobId = jobId;
    String accessToken = AppSettings.getAccessToken();
    Single<String> responseSingle;
    if (TextUtils.isEmpty(accessToken)) {
        responseSingle = mRawClient.getApiService().getLog(String.valueOf(mJobId));
    } else {
        String auth = String.format("token %1$s", AppSettings.getAccessToken());
        responseSingle = mRawClient.getApiService().getLog(auth, String.valueOf(mJobId));
    }
    Disposable subscription = responseSingle.subscribeOn(Schedulers.io()).map(s -> mRawClient.getLogUrl(mJobId)).onErrorResumeNext(new Function<Throwable, SingleSource<String>>() {

        @Override
        public SingleSource<String> apply(@NonNull Throwable throwable) throws Exception {
            String redirectUrl = "";
            HttpException httpException = (HttpException) throwable;
            Headers headers = httpException.response().headers();
            for (String header : headers.names()) {
                if (header.equals("Location")) {
                    redirectUrl = headers.get(header);
                    break;
                }
            }
            return Single.just(redirectUrl);
        }
    }).retry(LOAD_LOG_MAX_ATTEMPT).observeOn(AndroidSchedulers.mainThread()).subscribe((logUrl, throwable) -> {
        if (throwable == null) {
            getView().setLogUrl(logUrl);
        } else {
            getView().showLogError();
            getView().showLoadingError(throwable.getMessage());
        }
    });
    mSubscriptions.add(subscription);
}
Also used : CompositeDisposable(io.reactivex.disposables.CompositeDisposable) Disposable(io.reactivex.disposables.Disposable) Function(io.reactivex.functions.Function) Headers(okhttp3.Headers) NonNull(io.reactivex.annotations.NonNull) HttpException(retrofit2.HttpException)

Example 5 with NonNull

use of io.reactivex.annotations.NonNull in project Varis-Android by dkhmelenko.

the class RepositoriesPresenter method reloadRepos.

/**
     * Starts loading repositories
     */
public void reloadRepos() {
    String accessToken = AppSettings.getAccessToken();
    if (TextUtils.isEmpty(accessToken)) {
        Disposable subscription = mTravisRestClient.getApiService().getRepos("").subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(reposHandler());
        mSubscriptions.add(subscription);
    } else {
        Disposable subscription = mTravisRestClient.getApiService().getUser().doOnSuccess(this::cacheUserData).flatMap(new Function<User, SingleSource<List<Repo>>>() {

            @Override
            public SingleSource<List<Repo>> apply(@NonNull User user) throws Exception {
                String loginName = mUser.getLogin();
                return mTravisRestClient.getApiService().getUserRepos(loginName);
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(reposHandler());
        mSubscriptions.add(subscription);
    }
}
Also used : CompositeDisposable(io.reactivex.disposables.CompositeDisposable) Disposable(io.reactivex.disposables.Disposable) Function(io.reactivex.functions.Function) User(com.khmelenko.lab.varis.network.response.User) NonNull(io.reactivex.annotations.NonNull) List(java.util.List)

Aggregations

NonNull (io.reactivex.annotations.NonNull)39 Disposable (io.reactivex.disposables.Disposable)17 CompositeDisposable (io.reactivex.disposables.CompositeDisposable)15 Consumer (io.reactivex.functions.Consumer)14 Function (io.reactivex.functions.Function)13 BuildDetails (com.khmelenko.lab.varis.network.response.BuildDetails)6 OnClick (butterknife.OnClick)5 List (java.util.List)5 RequestBody (okhttp3.RequestBody)5 ObservableEmitter (io.reactivex.ObservableEmitter)4 ObservableOnSubscribe (io.reactivex.ObservableOnSubscribe)4 IOException (java.io.IOException)4 ArrayList (java.util.ArrayList)4 Headers (okhttp3.Headers)3 View (android.view.View)2 ANError (com.androidnetworking.error.ANError)2 User (com.khmelenko.lab.varis.network.response.User)2 LzyResponse (com.lzy.demo.model.LzyResponse)2 ServerModel (com.lzy.demo.model.ServerModel)2 Action (io.reactivex.functions.Action)2