Search in sources :

Example 1 with Observer

use of rx.Observer in project XRichText by sendtion.

the class NewActivity method insertImagesSync.

/**
 * 异步方式插入图片
 * @param data
 */
private void insertImagesSync(final Intent data) {
    insertDialog.show();
    subsInsert = Observable.create(new Observable.OnSubscribe<String>() {

        @Override
        public void call(Subscriber<? super String> subscriber) {
            try {
                et_new_content.measure(0, 0);
                int width = CommonUtil.getScreenWidth(NewActivity.this);
                int height = CommonUtil.getScreenHeight(NewActivity.this);
                ArrayList<String> photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                // 可以同时插入多张图片
                for (String imagePath : photos) {
                    // Log.i("NewActivity", "###path=" + imagePath);
                    // 压缩图片
                    Bitmap bitmap = ImageUtils.getSmallBitmap(imagePath, width, height);
                    // bitmap = BitmapFactory.decodeFile(imagePath);
                    imagePath = SDCardUtil.saveToSdCard(bitmap);
                    // Log.i("NewActivity", "###imagePath="+imagePath);
                    subscriber.onNext(imagePath);
                }
                subscriber.onCompleted();
            } catch (Exception e) {
                e.printStackTrace();
                subscriber.onError(e);
            }
        }
    }).onBackpressureBuffer().subscribeOn(// 生产事件在io
    Schedulers.io()).observeOn(// 消费事件在UI线程
    AndroidSchedulers.mainThread()).subscribe(new Observer<String>() {

        @Override
        public void onCompleted() {
            insertDialog.dismiss();
            et_new_content.addEditTextAtIndex(et_new_content.getLastIndex(), " ");
            showToast("图片插入成功");
        }

        @Override
        public void onError(Throwable e) {
            insertDialog.dismiss();
            showToast("图片插入失败:" + e.getMessage());
        }

        @Override
        public void onNext(String imagePath) {
            et_new_content.insertImage(imagePath, et_new_content.getMeasuredWidth());
        }
    });
}
Also used : Bitmap(android.graphics.Bitmap) Subscriber(rx.Subscriber) Observer(rx.Observer)

Example 2 with Observer

use of rx.Observer in project azure-tools-for-java by Microsoft.

the class ADLSGen2Deploy method deploy.

@Override
public Observable<String> deploy(File src, Observer<SparkLogLine> logSubject) {
    // four steps to upload via adls gen2 rest api
    // 1.put request to create new dir
    // 2.put request to create new file(artifact) which is empty
    // 3.patch request to append data to file
    // 4.patch request to flush data to file
    final URI destURI = getUploadDir();
    // remove request / end otherwise invalid url response
    final String destStr = destURI.toString();
    final String dirPath = destStr.endsWith("/") ? destStr.substring(0, destStr.length() - 1) : destStr;
    final String filePath = String.format("%s/%s", dirPath, src.getName());
    final ADLSGen2FSOperation op = new ADLSGen2FSOperation(this.http);
    return op.createDir(dirPath, "0755").onErrorReturn(err -> {
        if (err.getMessage() != null && (err.getMessage().contains(String.valueOf(HttpStatus.SC_FORBIDDEN)) || err.getMessage().contains(String.valueOf(HttpStatus.SC_NOT_FOUND)))) {
            // Sample destinationRootPath: https://accountName.dfs.core.windows.net/fsName/SparkSubmission/
            String fileSystemRootPath = UriUtil.normalizeWithSlashEnding(URI.create(destinationRootPath)).resolve("../").toString();
            String errorMessage = String.format("Failed to create folder %s when uploading Spark application artifacts with error: %s. %s", dirPath, err.getMessage(), getForbiddenErrorHints(fileSystemRootPath));
            throw new IllegalArgumentException(errorMessage);
        } else {
            throw Exceptions.propagate(err);
        }
    }).doOnNext(ignore -> log().info(String.format("Create filesystem %s successfully.", dirPath))).flatMap(ignore -> op.createFile(filePath, "0755")).flatMap(ignore -> op.uploadData(filePath, src)).doOnNext(ignore -> log().info(String.format("Append data to file %s successfully.", filePath))).map(ignored -> AbfsUri.parse(filePath).getUri().toString());
}
Also used : AuthMethodManager(com.microsoft.azuretools.authmanage.AuthMethodManager) NotNull(com.microsoft.azuretools.azurecommons.helpers.NotNull) JobUtils(com.microsoft.azure.hdinsight.spark.jobs.JobUtils) Exceptions(rx.exceptions.Exceptions) HttpStatus(org.apache.http.HttpStatus) Observer(rx.Observer) AbfsUri(com.microsoft.azure.hdinsight.common.AbfsUri) File(java.io.File) ILogger(com.microsoft.azure.hdinsight.common.logger.ILogger) HttpObservable(com.microsoft.azure.hdinsight.sdk.common.HttpObservable) ADLSGen2FSOperation(com.microsoft.azure.hdinsight.sdk.storage.adlsgen2.ADLSGen2FSOperation) Observable(rx.Observable) UriUtil(com.microsoft.azure.hdinsight.common.UriUtil) URI(java.net.URI) SparkLogLine(com.microsoft.azure.hdinsight.spark.common.log.SparkLogLine) ADLSGen2FSOperation(com.microsoft.azure.hdinsight.sdk.storage.adlsgen2.ADLSGen2FSOperation) URI(java.net.URI)

Example 3 with Observer

use of rx.Observer in project azure-tools-for-java by Microsoft.

the class WebHDFSDeploy method deploy.

@Override
public Observable<String> deploy(File src, Observer<SparkLogLine> logSubject) {
    // three steps to upload via webhdfs
    // 1.put request to create new dir
    // 2.put request to get 307 redirect uri from response
    // 3.put redirect request with file content as setEntity
    final URI dest = getUploadDir();
    final HttpPut req = new HttpPut(dest.toString());
    return http.request(req, null, this.createDirReqParams, null).doOnNext(resp -> {
        if (resp.getStatusLine().getStatusCode() != 200) {
            Exceptions.propagate(new UnknownServiceException("Can not create directory to save artifact using webHDFS storage type"));
        }
    }).map(ignored -> new HttpPut(dest.resolve(src.getName()).toString())).flatMap(put -> http.request(put, null, this.uploadReqParams, null)).map(resp -> resp.getFirstHeader("Location").getValue()).doOnNext(redirectedUri -> {
        if (StringUtils.isBlank(redirectedUri)) {
            Exceptions.propagate(new UnknownServiceException("Can not get valid redirect uri using webHDFS storage type"));
        }
    }).map(HttpPut::new).flatMap(put -> {
        try {
            InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(src), -1, ContentType.APPLICATION_OCTET_STREAM);
            reqEntity.setChunked(true);
            return http.request(put, new BufferedHttpEntity(reqEntity), URLEncodedUtils.parse(put.getURI(), "UTF-8"), null);
        } catch (IOException ex) {
            throw new RuntimeException(new IllegalArgumentException("Can not get local artifact when uploading" + ex.toString()));
        }
    }).map(ignored -> {
        try {
            return getArtifactUploadedPath(dest.resolve(src.getName()).toString());
        } catch (final URISyntaxException ex) {
            throw new RuntimeException(new IllegalArgumentException("Can not get valid artifact upload path" + ex.toString()));
        }
    });
}
Also used : NotNull(com.microsoft.azuretools.azurecommons.helpers.NotNull) Exceptions(rx.exceptions.Exceptions) URISyntaxException(java.net.URISyntaxException) RequestConfig(org.apache.http.client.config.RequestConfig) StringUtils(org.apache.commons.lang3.StringUtils) ILogger(com.microsoft.azure.hdinsight.common.logger.ILogger) Observable(rx.Observable) WebHdfsParamsBuilder(com.microsoft.azure.hdinsight.sdk.storage.webhdfs.WebHdfsParamsBuilder) URI(java.net.URI) IClusterDetail(com.microsoft.azure.hdinsight.sdk.cluster.IClusterDetail) Nullable(com.microsoft.azuretools.azurecommons.helpers.Nullable) URIBuilder(org.apache.http.client.utils.URIBuilder) JobUtils(com.microsoft.azure.hdinsight.spark.jobs.JobUtils) ContentType(org.apache.http.entity.ContentType) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) Observer(rx.Observer) File(java.io.File) HttpObservable(com.microsoft.azure.hdinsight.sdk.common.HttpObservable) List(java.util.List) HttpPut(org.apache.http.client.methods.HttpPut) URLEncodedUtils(org.apache.http.client.utils.URLEncodedUtils) InputStreamEntity(org.apache.http.entity.InputStreamEntity) NameValuePair(org.apache.http.NameValuePair) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) SparkLogLine(com.microsoft.azure.hdinsight.spark.common.log.SparkLogLine) UnknownServiceException(java.net.UnknownServiceException) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) UnknownServiceException(java.net.UnknownServiceException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) HttpPut(org.apache.http.client.methods.HttpPut) FileInputStream(java.io.FileInputStream) InputStreamEntity(org.apache.http.entity.InputStreamEntity)

Example 4 with Observer

use of rx.Observer in project Reader by TheKeeperOfPie.

the class FragmentNewPost method onCreateView.

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.fragment_new_post, container, false);
    layoutCoordinator = (CoordinatorLayout) view.findViewById(R.id.layout_coordinator);
    layoutAppBar = (AppBarLayout) view.findViewById(R.id.layout_app_bar);
    scrollText = (NestedScrollView) view.findViewById(R.id.scroll_text);
    textInfo = (TextView) view.findViewById(R.id.text_info);
    textSubmit = (TextView) view.findViewById(R.id.text_submit);
    editTextTitle = (EditText) view.findViewById(R.id.edit_title);
    editTextBody = (EditText) view.findViewById(R.id.edit_body);
    toolbar = (Toolbar) view.findViewById(R.id.toolbar);
    toolbar.setTitle(getString(R.string.new_post));
    toolbar.setTitleTextColor(themer.getColorFilterPrimary().getColor());
    toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
    toolbar.setNavigationOnClickListener(v -> {
        UtilsInput.hideKeyboard(editTextBody);
        mListener.onNavigationBackClick();
    });
    toolbar.getNavigationIcon().mutate().setColorFilter(themer.getColorFilterPrimary());
    setUpOptionsMenu();
    textInfo.setText(getString(R.string.submitting_post, getArguments().getString(SUBREDDIT), getArguments().getString(USER)));
    String submitTextHtml = getArguments().getString(SUBMIT_TEXT_HTML);
    Log.d(TAG, "submitTextHtml: " + submitTextHtml);
    if (TextUtils.isEmpty(submitTextHtml) || "null".equals(submitTextHtml)) {
        textSubmit.setVisibility(View.GONE);
    } else {
        textSubmit.setText(UtilsReddit.getFormattedHtml(submitTextHtml));
    }
    textSubmit.setMovementMethod(LinkMovementMethod.getInstance());
    if (Reddit.PostType.LINK == postType) {
        editTextBody.setHint("URL");
    } else {
        editTextBody.setHint("Text");
    }
    View.OnFocusChangeListener onFocusChangeListener = (v, hasFocus) -> {
        if (hasFocus) {
            AppBarLayout.Behavior behaviorAppBar = (AppBarLayout.Behavior) ((CoordinatorLayout.LayoutParams) layoutAppBar.getLayoutParams()).getBehavior();
            behaviorAppBar.onNestedFling(layoutCoordinator, layoutAppBar, null, 0, 1000, true);
        }
    };
    editTextTitle.setOnFocusChangeListener(onFocusChangeListener);
    editTextBody.setOnFocusChangeListener(onFocusChangeListener);
    editMarginDefault = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8, getResources().getDisplayMetrics());
    editMarginWithActions = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 56, getResources().getDisplayMetrics());
    textPreview = (TextView) view.findViewById(R.id.text_preview);
    viewDivider = view.findViewById(R.id.view_divider);
    toolbarActions = (Toolbar) view.findViewById(R.id.toolbar_actions);
    toolbarActions.inflateMenu(R.menu.menu_editor_actions);
    toolbarActions.setOnMenuItemClickListener(this);
    tabLayout = (TabLayout) view.findViewById(R.id.layout_tab);
    tabLayout.setTabMode(TabLayout.MODE_FIXED);
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
    tabLayout.setTabTextColors(themer.getColorFilterTextMuted().getColor(), themer.getColorFilterPrimary().getColor());
    viewPager = (ViewPager) view.findViewById(R.id.view_pager);
    viewPager.setAdapter(new PagerAdapter() {

        @Override
        public CharSequence getPageTitle(int position) {
            switch(position) {
                case PAGE_POST:
                    return getString(R.string.page_post);
                case PAGE_PREVIEW:
                    return getString(R.string.page_preview);
            }
            return super.getPageTitle(position);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            return viewPager.getChildAt(position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
        }

        @Override
        public int getCount() {
            if (Reddit.PostType.LINK == postType) {
                tabLayout.setVisibility(View.GONE);
                toolbarActions.setVisibility(View.GONE);
                viewDivider.setVisibility(View.GONE);
                itemHideActions.setVisible(false);
                return 1;
            }
            return viewPager.getChildCount();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
    });
    viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            if (position == PAGE_POST && toolbarActions.getVisibility() == View.VISIBLE) {
                float translationY = positionOffset * (toolbarActions.getHeight() + viewDivider.getHeight());
                viewDivider.setTranslationY(translationY);
                toolbarActions.setTranslationY(translationY);
            }
        }

        @Override
        public void onPageSelected(int position) {
            if (position == PAGE_PREVIEW) {
                if (editTextBody.length() == 0) {
                    textPreview.setText(R.string.empty_reply_preview);
                } else {
                    textPreview.setText(Html.fromHtml(Processor.process(editTextBody.getText().toString())));
                }
            }
            if (Reddit.PostType.SELF == postType) {
                itemHideActions.setVisible(position == PAGE_POST);
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    });
    tabLayout.setupWithViewPager(viewPager);
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    layoutCaptcha = (RelativeLayout) view.findViewById(R.id.layout_captcha);
    imageCaptcha = (ImageView) view.findViewById(R.id.image_captcha);
    editCaptcha = (EditText) view.findViewById(R.id.edit_captcha);
    buttonCaptchaRefresh = (ImageButton) view.findViewById(R.id.button_captcha_refresh);
    buttonCaptchaRefresh.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            loadCaptcha();
        }
    });
    if (getArguments().getBoolean(IS_EDIT, false)) {
        loadEditValues();
    } else {
        reddit.needsCaptcha().subscribe(new Observer<String>() {

            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onNext(String response) {
                if ("true".equalsIgnoreCase(response)) {
                    layoutCaptcha.setVisibility(View.VISIBLE);
                    loadCaptcha();
                }
            }
        });
    }
    view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {
            Menu menu = toolbarActions.getMenu();
            int maxNum = (int) (view.getWidth() / TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 48, getResources().getDisplayMetrics()));
            int numShown = 0;
            for (int index = 0; index < menu.size(); index++) {
                MenuItem menuItem = menu.getItem(index);
                menuItem.getIcon().setColorFilter(themer.getColorFilterIcon());
                if (numShown++ < maxNum - 1) {
                    menuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
                } else {
                    menuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
                }
            }
            // Toggle visibility to fix weird bug causing tabs to not be added
            tabLayout.setVisibility(View.GONE);
            tabLayout.setVisibility(View.VISIBLE);
            view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        }
    });
    return view;
}
Also used : AppBarLayout(android.support.design.widget.AppBarLayout) CoordinatorLayout(android.support.design.widget.CoordinatorLayout) ImageButton(android.widget.ImageButton) Bundle(android.os.Bundle) ControllerLinks(com.winsonchiu.reader.links.ControllerLinks) UtilsRx(com.winsonchiu.reader.utils.UtilsRx) ImageView(android.widget.ImageView) ViewPager(android.support.v4.view.ViewPager) LinkMovementMethod(android.text.method.LinkMovementMethod) MenuItem(android.view.MenuItem) TabLayout(android.support.design.widget.TabLayout) Inject(javax.inject.Inject) Picasso(com.squareup.picasso.Picasso) JSONException(org.json.JSONException) Reddit(com.winsonchiu.reader.data.reddit.Reddit) JSONObject(org.json.JSONObject) ComponentStatic(com.winsonchiu.reader.dagger.components.ComponentStatic) Toast(android.widget.Toast) Menu(android.view.Menu) Link(com.winsonchiu.reader.data.reddit.Link) View(android.view.View) JsonNode(com.fasterxml.jackson.databind.JsonNode) NestedScrollView(android.support.v4.widget.NestedScrollView) Log(android.util.Log) Processor(com.github.rjeschke.txtmark.Processor) UtilsInput(com.winsonchiu.reader.utils.UtilsInput) URLUtil(android.webkit.URLUtil) LayoutInflater(android.view.LayoutInflater) Listing(com.winsonchiu.reader.data.reddit.Listing) PagerAdapter(android.support.v4.view.PagerAdapter) TextUtils(android.text.TextUtils) Observer(rx.Observer) UtilsReddit(com.winsonchiu.reader.utils.UtilsReddit) ViewGroup(android.view.ViewGroup) TextView(android.widget.TextView) TypedValue(android.util.TypedValue) Toolbar(android.support.v7.widget.Toolbar) Html(android.text.Html) ViewTreeObserver(android.view.ViewTreeObserver) RelativeLayout(android.widget.RelativeLayout) Nullable(android.support.annotation.Nullable) Activity(android.app.Activity) EditText(android.widget.EditText) PagerAdapter(android.support.v4.view.PagerAdapter) TabLayout(android.support.design.widget.TabLayout) AppBarLayout(android.support.design.widget.AppBarLayout) Menu(android.view.Menu) ViewTreeObserver(android.view.ViewTreeObserver) ViewGroup(android.view.ViewGroup) MenuItem(android.view.MenuItem) ImageView(android.widget.ImageView) View(android.view.View) NestedScrollView(android.support.v4.widget.NestedScrollView) TextView(android.widget.TextView) ViewPager(android.support.v4.view.ViewPager) JSONObject(org.json.JSONObject)

Example 5 with Observer

use of rx.Observer in project CloudReader by youlookwhat.

the class EverydayModel method showRecyclerViewData.

/**
     * 显示RecyclerView数据
     */
public void showRecyclerViewData(final RequestImpl listener) {
    SPUtils.putString(HOME_ONE, "");
    SPUtils.putString(HOME_TWO, "");
    SPUtils.putString(HOME_SIX, "");
    Func1<GankIoDayBean, Observable<List<List<AndroidBean>>>> func1 = new Func1<GankIoDayBean, Observable<List<List<AndroidBean>>>>() {

        @Override
        public Observable<List<List<AndroidBean>>> call(GankIoDayBean gankIoDayBean) {
            List<List<AndroidBean>> lists = new ArrayList<>();
            GankIoDayBean.ResultsBean results = gankIoDayBean.getResults();
            if (results.getAndroid() != null && results.getAndroid().size() > 0) {
                addUrlList(lists, results.getAndroid(), "Android");
            }
            if (results.getWelfare() != null && results.getWelfare().size() > 0) {
                addUrlList(lists, results.getWelfare(), "福利");
            }
            if (results.getiOS() != null && results.getiOS().size() > 0) {
                addUrlList(lists, results.getiOS(), "IOS");
            }
            if (results.getRestMovie() != null && results.getRestMovie().size() > 0) {
                addUrlList(lists, results.getRestMovie(), "休息视频");
            }
            if (results.getResource() != null && results.getResource().size() > 0) {
                addUrlList(lists, results.getResource(), "拓展资源");
            }
            if (results.getRecommend() != null && results.getRecommend().size() > 0) {
                addUrlList(lists, results.getRecommend(), "瞎推荐");
            }
            if (results.getFront() != null && results.getFront().size() > 0) {
                addUrlList(lists, results.getFront(), "前端");
            }
            if (results.getApp() != null && results.getApp().size() > 0) {
                addUrlList(lists, results.getApp(), "App");
            }
            return Observable.just(lists);
        }
    };
    Observer<List<List<AndroidBean>>> observer = new Observer<List<List<AndroidBean>>>() {

        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
            listener.loadFailed();
        }

        @Override
        public void onNext(List<List<AndroidBean>> lists) {
            listener.loadSuccess(lists);
        }
    };
    Subscription subscription = HttpClient.Builder.getGankIOServer().getGankIoDay(year, month, day).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).flatMap(func1).subscribe(observer);
    listener.addSubscription(subscription);
}
Also used : ArrayList(java.util.ArrayList) Observable(rx.Observable) GankIoDayBean(com.example.jingbin.cloudreader.bean.GankIoDayBean) Observer(rx.Observer) ArrayList(java.util.ArrayList) List(java.util.List) Func1(rx.functions.Func1) Subscription(rx.Subscription) AndroidBean(com.example.jingbin.cloudreader.bean.AndroidBean)

Aggregations

Observer (rx.Observer)13 Observable (rx.Observable)7 Nullable (android.support.annotation.Nullable)3 TextUtils (android.text.TextUtils)3 Log (android.util.Log)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3 Subscription (rx.Subscription)3 Activity (android.app.Activity)2 Bundle (android.os.Bundle)2 AppBarLayout (android.support.design.widget.AppBarLayout)2 CoordinatorLayout (android.support.design.widget.CoordinatorLayout)2 TabLayout (android.support.design.widget.TabLayout)2 PagerAdapter (android.support.v4.view.PagerAdapter)2 ViewPager (android.support.v4.view.ViewPager)2 NestedScrollView (android.support.v4.widget.NestedScrollView)2 Toolbar (android.support.v7.widget.Toolbar)2 Html (android.text.Html)2 TypedValue (android.util.TypedValue)2 LayoutInflater (android.view.LayoutInflater)2