Search in sources :

Example 81 with Action0

use of rx.functions.Action0 in project Rutgers-Course-Tracker by tevjef.

the class SectionInfoPresenterImpl method loadRMP.

public void loadRMP() {
    final Iterable<Instructors> professorsNotFound = new ArrayList<>(mSection.getInstructors());
    cancePreviousSubscription();
    Subscriber<Professor> subscriber = new Subscriber<Professor>() {

        @Override
        public void onCompleted() {
        }

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

        @Override
        public void onNext(Professor professor) {
            if (getView() != null)
                getView().addRMPProfessor(professor);
        }
    };
    mSubscription = buildSearchParameters(mSection).flatMap(new Func1<Parameter, Observable<Professor>>() {

        @Override
        public Observable<Professor> call(Parameter parameter) {
            return rmp.getProfessor(parameter);
        }
    }).doOnNext(new Action1<Professor>() {

        @Override
        public void call(Professor professor) {
            for (final Iterator<Instructors> iterator = professorsNotFound.iterator(); iterator.hasNext(); ) {
                Instructors i = iterator.next();
                if (StringUtils.getJaroWinklerDistance(i.getLastName(), professor.getLastName()) > .70 || StringUtils.getJaroWinklerDistance(i.getLastName(), professor.getFirstName()) > .70) {
                    iterator.remove();
                }
            }
        }
    }).subscribeOn(mBackgroundThread).observeOn(mMainThread).doOnTerminate(new Action0() {

        @Override
        public void call() {
            if (getView() != null) {
                getView().showRatingsLayout();
                getView().hideRatingsLoading();
                for (Instructors i : professorsNotFound) {
                    getView().addErrorProfessor(i.getName());
                }
            }
        }
    }).subscribe(subscriber);
}
Also used : Professor(com.tevinjeffrey.rmp.common.Professor) Action0(rx.functions.Action0) Action1(rx.functions.Action1) ArrayList(java.util.ArrayList) Observable(rx.Observable) Instructors(com.tevinjeffrey.rutgersct.rutgersapi.model.Course.Section.Instructors) Subscriber(rx.Subscriber) Parameter(com.tevinjeffrey.rmp.common.Parameter)

Example 82 with Action0

use of rx.functions.Action0 in project Shuttle by timusus.

the class MusicService method openFile.

/**
     * Opens a file and prepares it for playback
     *
     * @param path The path of the file to open
     */
public void openFile(String path, @Nullable Action0 completion) {
    synchronized (this) {
        if (path == null) {
            return;
        }
        Uri uri = Uri.parse(path);
        long id = -1;
        try {
            id = Long.valueOf(uri.getLastPathSegment());
        } catch (NumberFormatException ignored) {
        }
        Predicate<Song> predicate;
        long finalId = id;
        if (finalId != -1 && (path.startsWith(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI.toString()) || path.startsWith(MediaStore.Files.getContentUri("external").toString()))) {
            predicate = song -> song.id == finalId;
        } else {
            if (uri != null && path.startsWith("content://")) {
                path = uri.getPath();
            }
            String finalPath = path;
            predicate = song -> song.path.contains(finalPath);
        }
        DataManager.getInstance().getSongsRelay().first().map(songs -> Stream.of(songs).filter(predicate).collect(Collectors.toList())).subscribe(songs -> {
            if (!songs.isEmpty()) {
                currentSong = songs.get(0);
                open(currentSong);
                if (completion != null) {
                    completion.call();
                }
            }
        });
    }
}
Also used : R(com.simplecity.amp_library.R) WidgetProviderSmall(com.simplecity.amp_library.ui.widgets.WidgetProviderSmall) Bundle(android.os.Bundle) WebImage(com.google.android.gms.common.images.WebImage) PackageManager(android.content.pm.PackageManager) CrashlyticsCore(com.crashlytics.android.core.CrashlyticsCore) PlaylistUtils(com.simplecity.amp_library.utils.PlaylistUtils) Uri(android.net.Uri) AndroidSchedulers(rx.android.schedulers.AndroidSchedulers) Random(java.util.Random) PendingIntent(android.app.PendingIntent) MediaSessionCompat(android.support.v4.media.session.MediaSessionCompat) Action1(rx.functions.Action1) Drawable(android.graphics.drawable.Drawable) IBinder(android.os.IBinder) WakeLock(android.os.PowerManager.WakeLock) Song(com.simplecity.amp_library.model.Song) Manifest(android.Manifest) SQLiteException(android.database.sqlite.SQLiteException) PowerManager(android.os.PowerManager) MediaMetadataCompat(android.support.v4.media.MediaMetadataCompat) Handler(android.os.Handler) Looper(android.os.Looper) MediaStore(android.provider.MediaStore) Map(java.util.Map) Schedulers(rx.schedulers.Schedulers) PreferenceManager(android.preference.PreferenceManager) PlaybackStateCompat(android.support.v4.media.session.PlaybackStateCompat) Log(android.util.Log) WidgetProviderLarge(com.simplecity.amp_library.ui.widgets.WidgetProviderLarge) RemoteViews(android.widget.RemoteViews) SimpleTarget(com.bumptech.glide.request.target.SimpleTarget) NotificationManager(android.app.NotificationManager) Service(android.app.Service) IntentFilter(android.content.IntentFilter) ContextCompat(android.support.v4.content.ContextCompat) MediaStatus(com.google.android.gms.cast.MediaStatus) MediaButtonIntentReceiver(com.simplecity.amp_library.utils.MediaButtonIntentReceiver) NoConnectionException(com.google.android.libraries.cast.companionlibrary.cast.exceptions.NoConnectionException) BuildConfig(com.simplecity.amp_library.BuildConfig) VideoCastManager(com.google.android.libraries.cast.companionlibrary.cast.VideoCastManager) BroadcastReceiver(android.content.BroadcastReceiver) SettingsManager(com.simplecity.amp_library.utils.SettingsManager) List(java.util.List) Action0(rx.functions.Action0) WidgetProviderMedium(com.simplecity.amp_library.ui.widgets.WidgetProviderMedium) Notification(android.app.Notification) GlideUtils(com.simplecity.amp_library.glide.utils.GlideUtils) ContentValues(android.content.ContentValues) Nullable(android.support.annotation.Nullable) BluetoothDevice(android.bluetooth.BluetoothDevice) Context(android.content.Context) Album(com.simplecity.amp_library.model.Album) Stream(com.annimon.stream.Stream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) DrawableUtils(com.simplecity.amp_library.utils.DrawableUtils) Intent(android.content.Intent) SystemClock(android.os.SystemClock) AudioManager(android.media.AudioManager) ApplicationMetadata(com.google.android.gms.cast.ApplicationMetadata) HttpServer(com.simplecity.amp_library.http.HttpServer) ArrayList(java.util.ArrayList) Observable(rx.Observable) GlideAnimation(com.bumptech.glide.request.animation.GlideAnimation) SuppressLint(android.annotation.SuppressLint) BluetoothHeadset(android.bluetooth.BluetoothHeadset) Toast(android.widget.Toast) DiskCacheStrategy(com.bumptech.glide.load.engine.DiskCacheStrategy) BluetoothA2dp(android.bluetooth.BluetoothA2dp) Build(android.os.Build) VideoCastConsumerImpl(com.google.android.libraries.cast.companionlibrary.cast.callbacks.VideoCastConsumerImpl) ShuttleUtils(com.simplecity.amp_library.utils.ShuttleUtils) TransientNetworkDisconnectionException(com.google.android.libraries.cast.companionlibrary.cast.exceptions.TransientNetworkDisconnectionException) EqualizerService(com.simplecity.amp_library.services.EqualizerService) Collectors(com.annimon.stream.Collectors) AlarmManager(android.app.AlarmManager) WidgetProviderExtraLarge(com.simplecity.amp_library.ui.widgets.WidgetProviderExtraLarge) ComponentName(android.content.ComponentName) MediaInfo(com.google.android.gms.cast.MediaInfo) TextUtils(android.text.TextUtils) CastException(com.google.android.libraries.cast.companionlibrary.cast.exceptions.CastException) AppWidgetManager(android.appwidget.AppWidgetManager) RemoteControlClient(android.media.RemoteControlClient) Glide(com.bumptech.glide.Glide) SharedPreferences(android.content.SharedPreferences) TreeMap(java.util.TreeMap) HandlerThread(android.os.HandlerThread) Bitmap(android.graphics.Bitmap) Crashlytics(com.crashlytics.android.Crashlytics) DataManager(com.simplecity.amp_library.utils.DataManager) OnAudioFocusChangeListener(android.media.AudioManager.OnAudioFocusChangeListener) Predicate(com.annimon.stream.function.Predicate) MediaMetadata(com.google.android.gms.cast.MediaMetadata) Collections(java.util.Collections) ContentUris(android.content.ContentUris) Song(com.simplecity.amp_library.model.Song) Uri(android.net.Uri)

Example 83 with Action0

use of rx.functions.Action0 in project RxLifecycle by trello.

the class MainActivity method onResume.

@Override
protected void onResume() {
    super.onResume();
    Log.d(TAG, "onResume()");
    // `this.<Long>` is necessary if you're compiling on JDK7 or below.
    //
    // If you're using JDK8+, then you can safely remove it.
    Observable.interval(1, TimeUnit.SECONDS).doOnUnsubscribe(new Action0() {

        @Override
        public void call() {
            Log.i(TAG, "Unsubscribing subscription from onResume()");
        }
    }).compose(this.<Long>bindUntilEvent(ActivityEvent.DESTROY)).subscribe(new Action1<Long>() {

        @Override
        public void call(Long num) {
            Log.i(TAG, "Started in onResume(), running until in onDestroy(): " + num);
        }
    });
}
Also used : Action0(rx.functions.Action0)

Example 84 with Action0

use of rx.functions.Action0 in project RxPermissions by tbruyelle.

the class MainActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    RxPermissions rxPermissions = new RxPermissions(this);
    rxPermissions.setLogging(true);
    setContentView(R.layout.act_main);
    surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
    RxView.clicks(findViewById(R.id.enableCamera)).compose(rxPermissions.ensureEach(Manifest.permission.CAMERA)).subscribe(new Action1<Permission>() {

        @Override
        public void call(Permission permission) {
            Log.i(TAG, "Permission result " + permission);
            if (permission.granted) {
                releaseCamera();
                camera = Camera.open(0);
                try {
                    camera.setPreviewDisplay(surfaceView.getHolder());
                    camera.startPreview();
                } catch (IOException e) {
                    Log.e(TAG, "Error while trying to display the camera preview", e);
                }
            } else if (permission.shouldShowRequestPermissionRationale) {
                // Denied permission without ask never again
                Toast.makeText(MainActivity.this, "Denied permission without ask never again", Toast.LENGTH_SHORT).show();
            } else {
                // Denied permission with ask never again
                // Need to go to the settings
                Toast.makeText(MainActivity.this, "Permission denied, can't enable the camera", Toast.LENGTH_SHORT).show();
            }
        }
    }, new Action1<Throwable>() {

        @Override
        public void call(Throwable t) {
            Log.e(TAG, "onError", t);
        }
    }, new Action0() {

        @Override
        public void call() {
            Log.i(TAG, "OnComplete");
        }
    });
}
Also used : Action0(rx.functions.Action0) RxPermissions(com.tbruyelle.rxpermissions.RxPermissions) Permission(com.tbruyelle.rxpermissions.Permission) IOException(java.io.IOException)

Example 85 with Action0

use of rx.functions.Action0 in project ribbon by Netflix.

the class NettyClientTest method testLoadBalancerThrottle.

@Test
public void testLoadBalancerThrottle() throws Exception {
    HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("/testAsync/throttle");
    IClientConfig config = DefaultClientConfigImpl.getClientConfigWithDefaultValues().set(IClientConfigKey.Keys.MaxAutoRetriesNextServer, 1).set(IClientConfigKey.Keys.OkToRetryOnAllOperations, true);
    BaseLoadBalancer lb = new BaseLoadBalancer(new DummyPing(), new AvailabilityFilteringRule());
    LoadBalancingHttpClient<ByteBuf, ByteBuf> lbObservables = RibbonTransport.newHttpClient(lb, config);
    Server server = new Server(host, port);
    lb.setServersList(Lists.newArrayList(server, server, server));
    Observable<HttpClientResponse<ByteBuf>> response = lbObservables.submit(request);
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Throwable> error = new AtomicReference<Throwable>();
    response.subscribe(new Action1<HttpClientResponse<ByteBuf>>() {

        @Override
        public void call(HttpClientResponse<ByteBuf> t1) {
            System.err.println("Get response: " + t1.getStatus().code());
            latch.countDown();
        }
    }, new Action1<Throwable>() {

        @Override
        public void call(Throwable t1) {
            error.set(t1);
            latch.countDown();
        }
    }, new Action0() {

        @Override
        public void call() {
            Thread.dumpStack();
            latch.countDown();
        }
    });
    latch.await();
    assertTrue(error.get() instanceof ClientException);
    ClientException ce = (ClientException) error.get();
    assertTrue(ce.toString(), ce.getErrorType() == ClientException.ErrorType.NUMBEROF_RETRIES_NEXTSERVER_EXCEEDED);
    assertEquals(2, lbObservables.getServerStats(server).getSuccessiveConnectionFailureCount());
}
Also used : Action0(rx.functions.Action0) HttpServer(com.sun.net.httpserver.HttpServer) Server(com.netflix.loadbalancer.Server) MockWebServer(com.google.mockwebserver.MockWebServer) BaseLoadBalancer(com.netflix.loadbalancer.BaseLoadBalancer) AtomicReference(java.util.concurrent.atomic.AtomicReference) ByteBuf(io.netty.buffer.ByteBuf) CountDownLatch(java.util.concurrent.CountDownLatch) DummyPing(com.netflix.loadbalancer.DummyPing) HttpClientResponse(io.reactivex.netty.protocol.http.client.HttpClientResponse) IClientConfig(com.netflix.client.config.IClientConfig) ClientException(com.netflix.client.ClientException) AvailabilityFilteringRule(com.netflix.loadbalancer.AvailabilityFilteringRule) Test(org.junit.Test)

Aggregations

Action0 (rx.functions.Action0)134 Subscription (rx.Subscription)58 Test (org.junit.Test)56 CountDownLatch (java.util.concurrent.CountDownLatch)50 Action1 (rx.functions.Action1)28 AtomicReference (java.util.concurrent.atomic.AtomicReference)23 ArrayList (java.util.ArrayList)16 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)16 List (java.util.List)15 Func1 (rx.functions.Func1)13 HystrixRuntimeException (com.netflix.hystrix.exception.HystrixRuntimeException)12 Observable (rx.Observable)12 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)11 OnClick (butterknife.OnClick)10 IOException (java.io.IOException)9 CommandStreamTest (com.netflix.hystrix.metric.CommandStreamTest)8 UiThreadTest (android.support.test.annotation.UiThreadTest)7 PluginTestVerifier (com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifier)7 TestCollapserTimer (com.netflix.hystrix.HystrixCollapserTest.TestCollapserTimer)7 Method (java.lang.reflect.Method)7