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());
}
});
}
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());
}
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()));
}
});
}
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;
}
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);
}
Aggregations