Search in sources :

Example 56 with Observable

use of io.reactivex.Observable in project Android-ReactiveLocation by mcharmas.

the class MainActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    lastKnownLocationView = (TextView) findViewById(R.id.last_known_location_view);
    updatableLocationView = (TextView) findViewById(R.id.updated_location_view);
    addressLocationView = (TextView) findViewById(R.id.address_for_location_view);
    currentActivityView = (TextView) findViewById(R.id.activity_recent_view);
    locationProvider = new ReactiveLocationProvider(getApplicationContext(), ReactiveLocationProviderConfiguration.builder().setRetryOnConnectionSuspended(true).build());
    lastKnownLocationObservable = locationProvider.getLastKnownLocation().observeOn(AndroidSchedulers.mainThread());
    final LocationRequest locationRequest = LocationRequest.create().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY).setNumUpdates(5).setInterval(100);
    locationUpdatesObservable = locationProvider.checkLocationSettings(new LocationSettingsRequest.Builder().addLocationRequest(locationRequest).setAlwaysShow(// Refrence: http://stackoverflow.com/questions/29824408/google-play-services-locationservices-api-new-option-never
    true).build()).doOnNext(new Consumer<LocationSettingsResult>() {

        @Override
        public void accept(LocationSettingsResult locationSettingsResult) {
            Status status = locationSettingsResult.getStatus();
            if (status.getStatusCode() == LocationSettingsStatusCodes.RESOLUTION_REQUIRED) {
                try {
                    status.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS);
                } catch (IntentSender.SendIntentException th) {
                    Log.e("MainActivity", "Error opening settings activity.", th);
                }
            }
        }
    }).flatMap(new Function<LocationSettingsResult, Observable<Location>>() {

        @Override
        public Observable<Location> apply(LocationSettingsResult locationSettingsResult) {
            return locationProvider.getUpdatedLocation(locationRequest);
        }
    }).observeOn(AndroidSchedulers.mainThread());
    addressObservable = locationProvider.getUpdatedLocation(locationRequest).flatMap(new Function<Location, Observable<List<Address>>>() {

        @Override
        public Observable<List<Address>> apply(Location location) {
            return locationProvider.getReverseGeocodeObservable(location.getLatitude(), location.getLongitude(), 1);
        }
    }).map(new Function<List<Address>, Address>() {

        @Override
        public Address apply(List<Address> addresses) {
            return addresses != null && !addresses.isEmpty() ? addresses.get(0) : null;
        }
    }).map(new AddressToStringFunc()).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
    activityObservable = locationProvider.getDetectedActivity(50).observeOn(AndroidSchedulers.mainThread());
}
Also used : Status(com.google.android.gms.common.api.Status) LocationRequest(com.google.android.gms.location.LocationRequest) LocationSettingsResult(com.google.android.gms.location.LocationSettingsResult) Address(android.location.Address) Observable(io.reactivex.Observable) Function(io.reactivex.functions.Function) Consumer(io.reactivex.functions.Consumer) List(java.util.List) ReactiveLocationProvider(pl.charmas.android.reactivelocation2.ReactiveLocationProvider) IntentSender(android.content.IntentSender) AddressToStringFunc(pl.charmas.android.reactivelocation2.sample.utils.AddressToStringFunc) Location(android.location.Location)

Example 57 with Observable

use of io.reactivex.Observable in project Android-ReactiveLocation by mcharmas.

the class PlacesActivity method onLocationPermissionGranted.

@Override
protected void onLocationPermissionGranted() {
    compositeDisposable = new CompositeDisposable();
    compositeDisposable.add(reactiveLocationProvider.getCurrentPlace(null).subscribe(new Consumer<PlaceLikelihoodBuffer>() {

        @Override
        public void accept(PlaceLikelihoodBuffer buffer) {
            PlaceLikelihood likelihood = buffer.get(0);
            if (likelihood != null) {
                currentPlaceView.setText(likelihood.getPlace().getName());
            }
            buffer.release();
        }
    }, new Consumer<Throwable>() {

        @Override
        public void accept(Throwable throwable) throws Exception {
            Log.e("PlacesActivity", "Error in observable", throwable);
        }
    }));
    Observable<String> queryObservable = RxTextView.textChanges(queryView).map(new Function<CharSequence, String>() {

        @Override
        public String apply(CharSequence charSequence) {
            return charSequence.toString();
        }
    }).debounce(1, TimeUnit.SECONDS).filter(new Predicate<String>() {

        @Override
        public boolean test(String s) {
            return !TextUtils.isEmpty(s);
        }
    });
    Observable<Location> lastKnownLocationObservable = reactiveLocationProvider.getLastKnownLocation();
    Observable<AutocompletePredictionBuffer> suggestionsObservable = Observable.combineLatest(queryObservable, lastKnownLocationObservable, new BiFunction<String, Location, QueryWithCurrentLocation>() {

        @Override
        public QueryWithCurrentLocation apply(String query, Location currentLocation) {
            return new QueryWithCurrentLocation(query, currentLocation);
        }
    }).flatMap(new Function<QueryWithCurrentLocation, Observable<AutocompletePredictionBuffer>>() {

        @Override
        public Observable<AutocompletePredictionBuffer> apply(QueryWithCurrentLocation q) {
            if (q.location == null)
                return Observable.empty();
            double latitude = q.location.getLatitude();
            double longitude = q.location.getLongitude();
            LatLngBounds bounds = new LatLngBounds(new LatLng(latitude - 0.05, longitude - 0.05), new LatLng(latitude + 0.05, longitude + 0.05));
            return reactiveLocationProvider.getPlaceAutocompletePredictions(q.query, bounds, null);
        }
    });
    compositeDisposable.add(suggestionsObservable.subscribe(new Consumer<AutocompletePredictionBuffer>() {

        @Override
        public void accept(AutocompletePredictionBuffer buffer) {
            List<AutocompleteInfo> infos = new ArrayList<>();
            for (AutocompletePrediction prediction : buffer) {
                infos.add(new AutocompleteInfo(prediction.getFullText(null).toString(), prediction.getPlaceId()));
            }
            buffer.release();
            placeSuggestionsList.setAdapter(new ArrayAdapter<>(PlacesActivity.this, android.R.layout.simple_list_item_1, infos));
        }
    }));
}
Also used : PlaceLikelihoodBuffer(com.google.android.gms.location.places.PlaceLikelihoodBuffer) AutocompletePredictionBuffer(com.google.android.gms.location.places.AutocompletePredictionBuffer) ArrayList(java.util.ArrayList) Consumer(io.reactivex.functions.Consumer) LatLng(com.google.android.gms.maps.model.LatLng) LatLngBounds(com.google.android.gms.maps.model.LatLngBounds) Observable(io.reactivex.Observable) BiFunction(io.reactivex.functions.BiFunction) AutocompletePrediction(com.google.android.gms.location.places.AutocompletePrediction) PlaceLikelihood(com.google.android.gms.location.places.PlaceLikelihood) CompositeDisposable(io.reactivex.disposables.CompositeDisposable) Location(android.location.Location)

Example 58 with Observable

use of io.reactivex.Observable in project AntennaPod by AntennaPod.

the class ImportExportPreferencesFragment method exportWithWriter.

private void exportWithWriter(ExportWriter exportWriter, final Uri uri) {
    Context context = getActivity();
    progressDialog.show();
    if (uri == null) {
        Observable<File> observable = new ExportWorker(exportWriter, getContext()).exportObservable();
        disposable = observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(output -> {
            Uri fileUri = FileProvider.getUriForFile(context.getApplicationContext(), context.getString(R.string.provider_authority), output);
            showExportSuccessDialog(output.toString(), fileUri);
        }, this::showExportErrorDialog, progressDialog::dismiss);
    } else {
        DocumentFileExportWorker worker = new DocumentFileExportWorker(exportWriter, context, uri);
        disposable = worker.exportObservable().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(output -> showExportSuccessDialog(output.getUri().toString(), output.getUri()), this::showExportErrorDialog, progressDialog::dismiss);
    }
}
Also used : Context(android.content.Context) Context(android.content.Context) Bundle(android.os.Bundle) AlertDialog(androidx.appcompat.app.AlertDialog) PackageManager(android.content.pm.PackageManager) ExportWriter(de.danoeh.antennapod.core.export.ExportWriter) NonNull(androidx.annotation.NonNull) Date(java.util.Date) Completable(io.reactivex.Completable) Uri(android.net.Uri) SimpleDateFormat(java.text.SimpleDateFormat) Intent(android.content.Intent) StartActivityForResult(androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult) GetContent(androidx.activity.result.contract.ActivityResultContracts.GetContent) PreferenceFragmentCompat(androidx.preference.PreferenceFragmentCompat) AndroidSchedulers(io.reactivex.android.schedulers.AndroidSchedulers) UserPreferences(de.danoeh.antennapod.core.preferences.UserPreferences) PodcastApp(de.danoeh.antennapod.PodcastApp) ExportWorker(de.danoeh.antennapod.asynctask.ExportWorker) OpmlWriter(de.danoeh.antennapod.core.export.opml.OpmlWriter) PreferenceActivity(de.danoeh.antennapod.activity.PreferenceActivity) Locale(java.util.Locale) OpmlImportActivity(de.danoeh.antennapod.activity.OpmlImportActivity) DatabaseExporter(de.danoeh.antennapod.core.storage.DatabaseExporter) Observable(io.reactivex.Observable) Schedulers(io.reactivex.schedulers.Schedulers) Log(android.util.Log) ActivityResultLauncher(androidx.activity.result.ActivityResultLauncher) R(de.danoeh.antennapod.R) ProgressDialog(android.app.ProgressDialog) File(java.io.File) ResolveInfo(android.content.pm.ResolveInfo) DocumentFileExportWorker(de.danoeh.antennapod.asynctask.DocumentFileExportWorker) Disposable(io.reactivex.disposables.Disposable) List(java.util.List) HtmlWriter(de.danoeh.antennapod.core.export.html.HtmlWriter) ActivityNotFoundException(android.content.ActivityNotFoundException) ActivityResultContracts(androidx.activity.result.contract.ActivityResultContracts) FileProvider(androidx.core.content.FileProvider) FavoritesWriter(de.danoeh.antennapod.core.export.favorites.FavoritesWriter) Activity(android.app.Activity) Snackbar(com.google.android.material.snackbar.Snackbar) ActivityResult(androidx.activity.result.ActivityResult) ExportWorker(de.danoeh.antennapod.asynctask.ExportWorker) DocumentFileExportWorker(de.danoeh.antennapod.asynctask.DocumentFileExportWorker) DocumentFileExportWorker(de.danoeh.antennapod.asynctask.DocumentFileExportWorker) File(java.io.File) Uri(android.net.Uri)

Example 59 with Observable

use of io.reactivex.Observable in project sqlbrite by square.

the class BriteDatabaseTest method setUp.

@Before
public void setUp() throws IOException {
    Configuration configuration = Configuration.builder(InstrumentationRegistry.getContext()).callback(testDb).name(dbFolder.newFile().getPath()).build();
    Factory factory = new FrameworkSQLiteOpenHelperFactory();
    SupportSQLiteOpenHelper helper = factory.create(configuration);
    real = helper.getWritableDatabase();
    SqlBrite.Logger logger = new SqlBrite.Logger() {

        @Override
        public void log(String message) {
            logs.add(message);
        }
    };
    ObservableTransformer<Query, Query> queryTransformer = new ObservableTransformer<Query, Query>() {

        @Override
        public ObservableSource<Query> apply(Observable<Query> upstream) {
            return upstream.takeUntil(killSwitch);
        }
    };
    db = new BriteDatabase(helper, logger, scheduler, queryTransformer);
}
Also used : Configuration(android.arch.persistence.db.SupportSQLiteOpenHelper.Configuration) Query(com.squareup.sqlbrite3.SqlBrite.Query) SimpleSQLiteQuery(android.arch.persistence.db.SimpleSQLiteQuery) Factory(android.arch.persistence.db.SupportSQLiteOpenHelper.Factory) FrameworkSQLiteOpenHelperFactory(android.arch.persistence.db.framework.FrameworkSQLiteOpenHelperFactory) Observable(io.reactivex.Observable) FrameworkSQLiteOpenHelperFactory(android.arch.persistence.db.framework.FrameworkSQLiteOpenHelperFactory) SupportSQLiteOpenHelper(android.arch.persistence.db.SupportSQLiteOpenHelper) ObservableTransformer(io.reactivex.ObservableTransformer) Before(org.junit.Before)

Example 60 with Observable

use of io.reactivex.Observable in project RxCache by VictorAlbertos.

the class ProcessorProvidersTest method getSubscriberCompleted.

private TestObserver getSubscriberCompleted(boolean hasCache, final boolean evictCache, boolean detailResponse, Loader loader, boolean useExpiredDataIfLoaderNotAvailable) {
    Observable observable;
    switch(loader) {
        case VALID:
            observable = Observable.just(new Mock("message"));
            break;
        case NULL:
            observable = Observable.error(new RuntimeException("No data"));
            break;
        default:
            observable = Observable.create(new ObservableOnSubscribe<Object>() {

                @Override
                public void subscribe(ObservableEmitter<Object> e) throws Exception {
                    throw new RuntimeException("error");
                }
            });
            break;
    }
    ConfigProvider configProvider = new ConfigProvider("mockKey", null, null, detailResponse, true, false, "", "", observable, new EvictProvider(evictCache));
    if (hasCache)
        twoLayersCacheMock.save("mockKey", "", "", new Mock("message"), configProvider.getLifeTimeMillis(), configProvider.isExpirable(), configProvider.isEncrypted());
    processorProvidersUT = new ProcessorProvidersBehaviour(twoLayersCacheMock, useExpiredDataIfLoaderNotAvailable, evictExpiredRecordsPersistence, getDeepCopy, doMigrations);
    TestObserver observerMock = processorProvidersUT.getData(configProvider).test();
    observerMock.awaitTerminalEvent();
    return observerMock;
}
Also used : ObservableOnSubscribe(io.reactivex.ObservableOnSubscribe) ConfigProvider(io.rx_cache2.ConfigProvider) EvictProvider(io.rx_cache2.EvictProvider) Observable(io.reactivex.Observable) ObservableEmitter(io.reactivex.ObservableEmitter) TestObserver(io.reactivex.observers.TestObserver)

Aggregations

Observable (io.reactivex.Observable)170 List (java.util.List)54 ArrayList (java.util.ArrayList)39 Test (org.junit.Test)36 Collectors (java.util.stream.Collectors)29 InOrder (org.mockito.InOrder)27 TestException (io.reactivex.exceptions.TestException)24 Page (io.nem.symbol.sdk.api.Page)19 Address (io.nem.symbol.sdk.model.account.Address)18 AndroidSchedulers (io.reactivex.android.schedulers.AndroidSchedulers)18 Disposable (io.reactivex.disposables.Disposable)18 Bundle (android.os.Bundle)17 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)16 Function (io.reactivex.functions.Function)15 TestObserver (io.reactivex.observers.TestObserver)15 Schedulers (io.reactivex.schedulers.Schedulers)15 Nullable (android.support.annotation.Nullable)14 MerkleStateInfo (io.nem.symbol.sdk.model.blockchain.MerkleStateInfo)14 ApiClient (io.nem.symbol.sdk.openapi.vertx.invoker.ApiClient)14 AsyncResult (io.vertx.core.AsyncResult)14