Search in sources :

Example 26 with Subscriber

use of rx.Subscriber in project wh-app-android by WhiteHouse.

the class FeedManager method updateFavorites.

public static void updateFavorites(Context ctx) {
    sFavoritesSubject.onNext(Observable.create((Subscriber<? super List<FeedItem>> op) -> {
        final FavoritesMap map;
        final InputStreamReader isr;
        final List<FeedItem> favorites = new ArrayList<>();
        final Gson gson = GsonUtils.createGsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
        try {
            isr = new InputStreamReader(FavoritesUtils.getInputStream(ctx));
            map = gson.fromJson(isr, FavoritesMap.class);
            if (map.articles() != null) {
                processAndStoreFavorites(map.articles(), favorites, FeedType.TYPE_ARTICLE);
            }
            if (map.photos() != null) {
                processAndStoreFavorites(map.photos(), favorites, FeedType.TYPE_PHOTO);
            }
            if (map.videos() != null) {
                processAndStoreFavorites(map.videos(), favorites, FeedType.TYPE_VIDEO);
            }
            Collections.sort(favorites, (lhs, rhs) -> {
                if (lhs.feedTitle() != null && rhs.feedTitle() != null) {
                    return lhs.feedTitle().compareTo(rhs.feedTitle());
                }
                return 1;
            });
        } catch (FileNotFoundException ignored) {
        }
        op.onNext(favorites);
        op.onCompleted();
    }).subscribeOn(Schedulers.io()));
}
Also used : InputStreamReader(java.io.InputStreamReader) FeedItem(gov.whitehouse.data.model.FeedItem) Subscriber(rx.Subscriber) ArrayList(java.util.ArrayList) FileNotFoundException(java.io.FileNotFoundException) FavoritesMap(gov.whitehouse.data.model.FavoritesMap) Gson(com.google.gson.Gson) ArrayList(java.util.ArrayList) List(java.util.List)

Example 27 with Subscriber

use of rx.Subscriber in project AntennaPod by AntennaPod.

the class OnlineFeedViewActivity method parseFeed.

private void parseFeed() {
    if (feed == null || feed.getFile_url() == null && feed.isDownloaded()) {
        throw new IllegalStateException("feed must be non-null and downloaded when parseFeed is called");
    }
    Log.d(TAG, "Parsing feed");
    parser = Observable.create(new Observable.OnSubscribe<FeedHandlerResult>() {

        @Override
        public void call(Subscriber<? super FeedHandlerResult> subscriber) {
            FeedHandler handler = new FeedHandler();
            try {
                FeedHandlerResult result = handler.parseFeed(feed);
                subscriber.onNext(result);
            } catch (UnsupportedFeedtypeException e) {
                Log.d(TAG, "Unsupported feed type detected");
                if (TextUtils.equals("html", e.getRootElement().toLowerCase())) {
                    showFeedDiscoveryDialog(new File(feed.getFile_url()), feed.getDownload_url());
                } else {
                    subscriber.onError(e);
                }
            } catch (Exception e) {
                Log.e(TAG, Log.getStackTraceString(e));
                subscriber.onError(e);
            } finally {
                boolean rc = new File(feed.getFile_url()).delete();
                Log.d(TAG, "Deleted feed source file. Result: " + rc);
                subscriber.onCompleted();
            }
        }
    }).subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()).subscribe(result -> {
        beforeShowFeedInformation(result.feed);
        showFeedInformation(result.feed, result.alternateFeedUrls);
    }, error -> {
        String errorMsg = DownloadError.ERROR_PARSER_EXCEPTION.getErrorString(OnlineFeedViewActivity.this) + " (" + error.getMessage() + ")";
        showErrorDialog(errorMsg);
    });
}
Also used : LinearLayout(android.widget.LinearLayout) Bundle(android.os.Bundle) ProgressBar(android.widget.ProgressBar) DownloadRequestException(de.danoeh.antennapod.core.storage.DownloadRequestException) ImageView(android.widget.ImageView) AndroidSchedulers(rx.android.schedulers.AndroidSchedulers) StringUtils(org.apache.commons.lang3.StringUtils) DownloadRequestErrorDialogCreator(de.danoeh.antennapod.core.dialog.DownloadRequestErrorDialogCreator) NavUtils(android.support.v4.app.NavUtils) UserPreferences(de.danoeh.antennapod.core.preferences.UserPreferences) FeedItemlistDescriptionAdapter(de.danoeh.antennapod.adapter.FeedItemlistDescriptionAdapter) Looper(android.os.Looper) Map(java.util.Map) HtmlToPlainText(de.danoeh.antennapod.core.util.syndication.HtmlToPlainText) Schedulers(rx.schedulers.Schedulers) View(android.view.View) Button(android.widget.Button) AdapterView(android.widget.AdapterView) DownloadStatus(de.danoeh.antennapod.core.service.download.DownloadStatus) Log(android.util.Log) DownloadError(de.danoeh.antennapod.core.util.DownloadError) FileNameGenerator(de.danoeh.antennapod.core.util.FileNameGenerator) FeedDiscoverer(de.danoeh.antennapod.core.util.syndication.FeedDiscoverer) AppCompatActivity(android.support.v7.app.AppCompatActivity) FeedPreferences(de.danoeh.antennapod.core.feed.FeedPreferences) List(java.util.List) TextView(android.widget.TextView) DownloadEvent(de.danoeh.antennapod.core.event.DownloadEvent) Document(org.jsoup.nodes.Document) UnsupportedFeedtypeException(de.danoeh.antennapod.core.syndication.handler.UnsupportedFeedtypeException) RelativeLayout(android.widget.RelativeLayout) ListView(android.widget.ListView) Jsoup(org.jsoup.Jsoup) Subscription(rx.Subscription) FeedHandlerResult(de.danoeh.antennapod.core.syndication.handler.FeedHandlerResult) Context(android.content.Context) EventBus(de.greenrobot.event.EventBus) AuthenticationDialog(de.danoeh.antennapod.dialog.AuthenticationDialog) Dialog(android.app.Dialog) Intent(android.content.Intent) ApGlideSettings(de.danoeh.antennapod.core.glide.ApGlideSettings) MenuItem(android.view.MenuItem) ArrayList(java.util.ArrayList) Observable(rx.Observable) HttpDownloader(de.danoeh.antennapod.core.service.download.HttpDownloader) FeedHandler(de.danoeh.antennapod.core.syndication.handler.FeedHandler) DownloadRequest(de.danoeh.antennapod.core.service.download.DownloadRequest) Feed(de.danoeh.antennapod.core.feed.Feed) StorageUtils(de.danoeh.antennapod.core.util.StorageUtils) DialogInterface(android.content.DialogInterface) Downloader(de.danoeh.antennapod.core.service.download.Downloader) Subscriber(rx.Subscriber) LayoutInflater(android.view.LayoutInflater) R(de.danoeh.antennapod.R) TextUtils(android.text.TextUtils) IOException(java.io.IOException) EventDistributor(de.danoeh.antennapod.core.feed.EventDistributor) File(java.io.File) Spinner(android.widget.Spinner) FeedItem(de.danoeh.antennapod.core.feed.FeedItem) ArrayAdapter(android.widget.ArrayAdapter) AlertDialog(android.support.v7.app.AlertDialog) Glide(com.bumptech.glide.Glide) URLChecker(de.danoeh.antennapod.core.util.URLChecker) DBReader(de.danoeh.antennapod.core.storage.DBReader) DownloadRequester(de.danoeh.antennapod.core.storage.DownloadRequester) UnsupportedFeedtypeException(de.danoeh.antennapod.core.syndication.handler.UnsupportedFeedtypeException) FeedHandler(de.danoeh.antennapod.core.syndication.handler.FeedHandler) FeedHandlerResult(de.danoeh.antennapod.core.syndication.handler.FeedHandlerResult) File(java.io.File) Observable(rx.Observable) DownloadRequestException(de.danoeh.antennapod.core.storage.DownloadRequestException) UnsupportedFeedtypeException(de.danoeh.antennapod.core.syndication.handler.UnsupportedFeedtypeException) IOException(java.io.IOException)

Example 28 with Subscriber

use of rx.Subscriber in project AntennaPod by AntennaPod.

the class OnlineFeedViewActivity method startFeedDownload.

private void startFeedDownload(String url, String username, String password) {
    Log.d(TAG, "Starting feed download");
    url = URLChecker.prepareURL(url);
    feed = new Feed(url, null);
    if (username != null && password != null) {
        feed.setPreferences(new FeedPreferences(0, false, FeedPreferences.AutoDeleteAction.GLOBAL, username, password));
    }
    String fileUrl = new File(getExternalCacheDir(), FileNameGenerator.generateFileName(feed.getDownload_url())).toString();
    feed.setFile_url(fileUrl);
    final DownloadRequest request = new DownloadRequest(feed.getFile_url(), feed.getDownload_url(), "OnlineFeed", 0, Feed.FEEDFILETYPE_FEED, username, password, true, null);
    download = Observable.create(new Observable.OnSubscribe<DownloadStatus>() {

        @Override
        public void call(Subscriber<? super DownloadStatus> subscriber) {
            feeds = DBReader.getFeedList();
            downloader = new HttpDownloader(request);
            downloader.call();
            Log.d(TAG, "Download was completed");
            subscriber.onNext(downloader.getResult());
            subscriber.onCompleted();
        }
    }).subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()).subscribe(this::checkDownloadResult, error -> Log.e(TAG, Log.getStackTraceString(error)));
}
Also used : FeedPreferences(de.danoeh.antennapod.core.feed.FeedPreferences) LinearLayout(android.widget.LinearLayout) Bundle(android.os.Bundle) ProgressBar(android.widget.ProgressBar) DownloadRequestException(de.danoeh.antennapod.core.storage.DownloadRequestException) ImageView(android.widget.ImageView) AndroidSchedulers(rx.android.schedulers.AndroidSchedulers) StringUtils(org.apache.commons.lang3.StringUtils) DownloadRequestErrorDialogCreator(de.danoeh.antennapod.core.dialog.DownloadRequestErrorDialogCreator) NavUtils(android.support.v4.app.NavUtils) UserPreferences(de.danoeh.antennapod.core.preferences.UserPreferences) FeedItemlistDescriptionAdapter(de.danoeh.antennapod.adapter.FeedItemlistDescriptionAdapter) Looper(android.os.Looper) Map(java.util.Map) HtmlToPlainText(de.danoeh.antennapod.core.util.syndication.HtmlToPlainText) Schedulers(rx.schedulers.Schedulers) View(android.view.View) Button(android.widget.Button) AdapterView(android.widget.AdapterView) DownloadStatus(de.danoeh.antennapod.core.service.download.DownloadStatus) Log(android.util.Log) DownloadError(de.danoeh.antennapod.core.util.DownloadError) FileNameGenerator(de.danoeh.antennapod.core.util.FileNameGenerator) FeedDiscoverer(de.danoeh.antennapod.core.util.syndication.FeedDiscoverer) AppCompatActivity(android.support.v7.app.AppCompatActivity) FeedPreferences(de.danoeh.antennapod.core.feed.FeedPreferences) List(java.util.List) TextView(android.widget.TextView) DownloadEvent(de.danoeh.antennapod.core.event.DownloadEvent) Document(org.jsoup.nodes.Document) UnsupportedFeedtypeException(de.danoeh.antennapod.core.syndication.handler.UnsupportedFeedtypeException) RelativeLayout(android.widget.RelativeLayout) ListView(android.widget.ListView) Jsoup(org.jsoup.Jsoup) Subscription(rx.Subscription) FeedHandlerResult(de.danoeh.antennapod.core.syndication.handler.FeedHandlerResult) Context(android.content.Context) EventBus(de.greenrobot.event.EventBus) AuthenticationDialog(de.danoeh.antennapod.dialog.AuthenticationDialog) Dialog(android.app.Dialog) Intent(android.content.Intent) ApGlideSettings(de.danoeh.antennapod.core.glide.ApGlideSettings) MenuItem(android.view.MenuItem) ArrayList(java.util.ArrayList) Observable(rx.Observable) HttpDownloader(de.danoeh.antennapod.core.service.download.HttpDownloader) FeedHandler(de.danoeh.antennapod.core.syndication.handler.FeedHandler) DownloadRequest(de.danoeh.antennapod.core.service.download.DownloadRequest) Feed(de.danoeh.antennapod.core.feed.Feed) StorageUtils(de.danoeh.antennapod.core.util.StorageUtils) DialogInterface(android.content.DialogInterface) Downloader(de.danoeh.antennapod.core.service.download.Downloader) Subscriber(rx.Subscriber) LayoutInflater(android.view.LayoutInflater) R(de.danoeh.antennapod.R) TextUtils(android.text.TextUtils) IOException(java.io.IOException) EventDistributor(de.danoeh.antennapod.core.feed.EventDistributor) File(java.io.File) Spinner(android.widget.Spinner) FeedItem(de.danoeh.antennapod.core.feed.FeedItem) ArrayAdapter(android.widget.ArrayAdapter) AlertDialog(android.support.v7.app.AlertDialog) Glide(com.bumptech.glide.Glide) URLChecker(de.danoeh.antennapod.core.util.URLChecker) DBReader(de.danoeh.antennapod.core.storage.DBReader) DownloadRequester(de.danoeh.antennapod.core.storage.DownloadRequester) HttpDownloader(de.danoeh.antennapod.core.service.download.HttpDownloader) DownloadStatus(de.danoeh.antennapod.core.service.download.DownloadStatus) DownloadRequest(de.danoeh.antennapod.core.service.download.DownloadRequest) File(java.io.File) Observable(rx.Observable) Feed(de.danoeh.antennapod.core.feed.Feed)

Example 29 with Subscriber

use of rx.Subscriber in project AntennaPod by AntennaPod.

the class ProxyDialog method test.

private void test() {
    if (subscription != null) {
        subscription.unsubscribe();
    }
    if (!checkValidity()) {
        setTestRequired(true);
        return;
    }
    TypedArray res = context.getTheme().obtainStyledAttributes(new int[] { android.R.attr.textColorPrimary });
    int textColorPrimary = res.getColor(0, 0);
    res.recycle();
    String checking = context.getString(R.string.proxy_checking);
    txtvMessage.setTextColor(textColorPrimary);
    txtvMessage.setText("{fa-circle-o-notch spin} " + checking);
    txtvMessage.setVisibility(View.VISIBLE);
    subscription = Observable.create(new Observable.OnSubscribe<Response>() {

        @Override
        public void call(Subscriber<? super Response> subscriber) {
            String type = (String) spType.getSelectedItem();
            String host = etHost.getText().toString();
            String port = etPort.getText().toString();
            String username = etUsername.getText().toString();
            String password = etPassword.getText().toString();
            int portValue = 8080;
            if (!TextUtils.isEmpty(port)) {
                portValue = Integer.valueOf(port);
            }
            SocketAddress address = InetSocketAddress.createUnresolved(host, portValue);
            Proxy.Type proxyType = Proxy.Type.valueOf(type.toUpperCase());
            Proxy proxy = new Proxy(proxyType, address);
            OkHttpClient.Builder builder = AntennapodHttpClient.newBuilder().connectTimeout(10, TimeUnit.SECONDS).proxy(proxy);
            builder.interceptors().clear();
            OkHttpClient client = builder.build();
            if (!TextUtils.isEmpty(username)) {
                String credentials = Credentials.basic(username, password);
                client.interceptors().add(chain -> {
                    Request request = chain.request().newBuilder().header("Proxy-Authorization", credentials).build();
                    return chain.proceed(request);
                });
            }
            Request request = new Request.Builder().url("http://www.google.com").head().build();
            try {
                Response response = client.newCall(request).execute();
                subscriber.onNext(response);
            } catch (IOException e) {
                subscriber.onError(e);
            }
            subscriber.onCompleted();
        }
    }).subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()).subscribe(response -> {
        int colorId;
        String icon;
        String result;
        if (response.isSuccessful()) {
            colorId = R.color.download_success_green;
            icon = "{fa-check}";
            result = context.getString(R.string.proxy_test_successful);
        } else {
            colorId = R.color.download_failed_red;
            icon = "{fa-close}";
            result = context.getString(R.string.proxy_test_failed);
        }
        int color = ContextCompat.getColor(context, colorId);
        txtvMessage.setTextColor(color);
        String message = String.format("%s %s: %s", icon, result, response.message());
        txtvMessage.setText(message);
        setTestRequired(!response.isSuccessful());
    }, error -> {
        String icon = "{fa-close}";
        String result = context.getString(R.string.proxy_test_failed);
        int color = ContextCompat.getColor(context, R.color.download_failed_red);
        txtvMessage.setTextColor(color);
        String message = String.format("%s %s: %s", icon, result, error.getMessage());
        txtvMessage.setText(message);
        setTestRequired(true);
    });
}
Also used : Context(android.content.Context) SocketAddress(java.net.SocketAddress) AndroidSchedulers(rx.android.schedulers.AndroidSchedulers) Dialog(android.app.Dialog) Editable(android.text.Editable) TypedArray(android.content.res.TypedArray) Observable(rx.Observable) UserPreferences(de.danoeh.antennapod.core.preferences.UserPreferences) MDButton(com.afollestad.materialdialogs.internal.MDButton) Patterns(android.util.Patterns) Proxy(java.net.Proxy) Schedulers(rx.schedulers.Schedulers) View(android.view.View) Response(okhttp3.Response) AdapterView(android.widget.AdapterView) AntennapodHttpClient(de.danoeh.antennapod.core.service.download.AntennapodHttpClient) Request(okhttp3.Request) Subscriber(rx.Subscriber) R(de.danoeh.antennapod.R) ContextCompat(android.support.v4.content.ContextCompat) TextUtils(android.text.TextUtils) DialogAction(com.afollestad.materialdialogs.DialogAction) IOException(java.io.IOException) Credentials(okhttp3.Credentials) InetSocketAddress(java.net.InetSocketAddress) ProxyConfig(de.danoeh.antennapod.core.service.download.ProxyConfig) Spinner(android.widget.Spinner) TimeUnit(java.util.concurrent.TimeUnit) ArrayAdapter(android.widget.ArrayAdapter) TextView(android.widget.TextView) OkHttpClient(okhttp3.OkHttpClient) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Subscription(rx.Subscription) EditText(android.widget.EditText) TextWatcher(android.text.TextWatcher) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) IOException(java.io.IOException) Observable(rx.Observable) Response(okhttp3.Response) Proxy(java.net.Proxy) TypedArray(android.content.res.TypedArray) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress)

Example 30 with Subscriber

use of rx.Subscriber in project AndroidDevelop by 7449.

the class MainActivity method onPictureTaken.

@Override
public void onPictureTaken(CameraView cameraView, final byte[] data) {
    subscribe = Observable.create(new Observable.OnSubscribe<String>() {

        @Override
        public void call(Subscriber<? super String> subscriber) {
            try {
                File file = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "picture.jpg");
                OutputStream os = new FileOutputStream(file);
                os.write(data);
                subscriber.onNext(getExternalFilesDir(Environment.DIRECTORY_PICTURES).getPath());
                subscriber.onCompleted();
                os.flush();
                os.close();
            } catch (IOException ignored) {
                subscriber.onError(ignored);
            }
        }
    }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {

        @Override
        public void onCompleted() {
            Toast.makeText(getApplicationContext(), "保存成功", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onError(Throwable e) {
            Log.i(getClass().getSimpleName(), e.toString());
            Toast.makeText(getApplicationContext(), "保存失败——> " + e.toString(), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onNext(String s) {
            Toast.makeText(getApplicationContext(), "保存路径为:-->  " + s, Toast.LENGTH_SHORT).show();
        }
    });
}
Also used : Subscriber(rx.Subscriber) FileOutputStream(java.io.FileOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) File(java.io.File) Observable(rx.Observable)

Aggregations

Subscriber (rx.Subscriber)48 List (java.util.List)16 Observable (rx.Observable)15 IOException (java.io.IOException)11 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)10 Action1 (rx.functions.Action1)10 Schedulers (rx.schedulers.Schedulers)10 Context (android.content.Context)8 ArrayList (java.util.ArrayList)8 OnSubscribe (rx.Observable.OnSubscribe)8 TestCircuitBreaker (com.netflix.hystrix.HystrixCircuitBreakerTest.TestCircuitBreaker)7 RxException (com.yydcdut.note.model.rx.exception.RxException)7 Notification (rx.Notification)7 TestSubscriber (rx.observers.TestSubscriber)7 Cursor (android.database.Cursor)5 ContextLife (com.yydcdut.note.injector.ContextLife)5 Map (java.util.Map)5 Inject (javax.inject.Inject)5 Subscription (rx.Subscription)5 Action0 (rx.functions.Action0)5