Search in sources :

Example 36 with Observable

use of io.reactivex.Observable in project Shuttle by timusus.

the class PlaylistFragment method refreshAdapterItems.

private void refreshAdapterItems() {
    PermissionUtils.RequestStoragePermissions(() -> {
        if (getActivity() != null && isAdded()) {
            Observable<List<Playlist>> defaultPlaylistsObservable = Observable.defer(() -> {
                List<Playlist> playlists = new ArrayList<>();
                Playlist podcastPlaylist = Playlist.podcastPlaylist();
                if (podcastPlaylist != null) {
                    playlists.add(podcastPlaylist);
                }
                playlists.add(Playlist.recentlyAddedPlaylist);
                playlists.add(Playlist.mostPlayedPlaylist);
                return Observable.just(playlists);
            });
            Observable<List<Playlist>> playlistsObservable = DataManager.getInstance().getPlaylistsRelay();
            disposable = Observable.combineLatest(defaultPlaylistsObservable, playlistsObservable, (defaultPlaylists, playlists) -> {
                List<Playlist> list = new ArrayList<>();
                list.addAll(defaultPlaylists);
                list.addAll(playlists);
                return list;
            }).debounce(150, TimeUnit.MILLISECONDS).subscribeOn(Schedulers.io()).map(playlists -> {
                PlaylistView.OnClickListener listener = new PlaylistView.OnClickListener() {

                    @Override
                    public void onPlaylistClick(int position, PlaylistView playlistView) {
                        if (playlistClickListener != null) {
                            playlistClickListener.onPlaylistClicked(playlistView.playlist);
                        }
                    }

                    @Override
                    public void onPlaylistOverflowClick(int position, View v, Playlist playlist) {
                        PopupMenu menu = new PopupMenu(PlaylistFragment.this.getActivity(), v);
                        MenuUtils.setupPlaylistMenu(menu, playlist);
                        menu.setOnMenuItemClickListener(MenuUtils.getPlaylistPopupMenuClickListener(getContext(), playlist, null));
                        menu.show();
                    }
                };
                return Stream.of(playlists).sorted((a, b) -> ComparisonUtils.compare(a.name, b.name)).sorted((a, b) -> ComparisonUtils.compareInt(a.type, b.type)).map(playlist -> {
                    PlaylistView playlistView = new PlaylistView(playlist);
                    playlistView.setListener(listener);
                    return (ViewModel) playlistView;
                }).toList();
            }).observeOn(AndroidSchedulers.mainThread()).subscribe(items -> {
                if (items.isEmpty()) {
                    adapter.setItems(Collections.singletonList(new EmptyView(R.string.empty_playlist)));
                } else {
                    adapter.setItems(items);
                }
            }, error -> LogUtils.logException(TAG, "Error refreshing adapter", error));
        }
    });
}
Also used : R(com.simplecity.amp_library.R) Context(android.content.Context) Bundle(android.os.Bundle) Stream(com.annimon.stream.Stream) RecyclerListener(com.simplecityapps.recycler_adapter.recyclerview.RecyclerListener) EmptyView(com.simplecity.amp_library.ui.modelviews.EmptyView) ViewModelAdapter(com.simplecityapps.recycler_adapter.adapter.ViewModelAdapter) ViewModel(com.simplecityapps.recycler_adapter.model.ViewModel) AndroidSchedulers(io.reactivex.android.schedulers.AndroidSchedulers) ArrayList(java.util.ArrayList) MenuUtils(com.simplecity.amp_library.utils.MenuUtils) PlaylistView(com.simplecity.amp_library.ui.modelviews.PlaylistView) View(android.view.View) Observable(io.reactivex.Observable) Schedulers(io.reactivex.schedulers.Schedulers) FastScrollRecyclerView(com.simplecityapps.recyclerview_fastscroll.views.FastScrollRecyclerView) LogUtils(com.simplecity.amp_library.utils.LogUtils) LayoutInflater(android.view.LayoutInflater) Playlist(com.simplecity.amp_library.model.Playlist) LinearLayoutManager(android.support.v7.widget.LinearLayoutManager) PopupMenu(android.support.v7.widget.PopupMenu) ViewGroup(android.view.ViewGroup) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) Disposable(io.reactivex.disposables.Disposable) PermissionUtils(com.simplecity.amp_library.utils.PermissionUtils) ComparisonUtils(com.simplecity.amp_library.utils.ComparisonUtils) DataManager(com.simplecity.amp_library.utils.DataManager) Nullable(android.support.annotation.Nullable) Collections(java.util.Collections) ArrayList(java.util.ArrayList) ViewModel(com.simplecityapps.recycler_adapter.model.ViewModel) EmptyView(com.simplecity.amp_library.ui.modelviews.EmptyView) PlaylistView(com.simplecity.amp_library.ui.modelviews.PlaylistView) View(android.view.View) FastScrollRecyclerView(com.simplecityapps.recyclerview_fastscroll.views.FastScrollRecyclerView) Playlist(com.simplecity.amp_library.model.Playlist) PlaylistView(com.simplecity.amp_library.ui.modelviews.PlaylistView) ArrayList(java.util.ArrayList) List(java.util.List) EmptyView(com.simplecity.amp_library.ui.modelviews.EmptyView) PopupMenu(android.support.v7.widget.PopupMenu)

Example 37 with Observable

use of io.reactivex.Observable in project Shuttle by timusus.

the class SuggestedFragment method getRecentlyAddedViewModels.

Observable<List<ViewModel>> getRecentlyAddedViewModels() {
    return Playlist.recentlyAddedPlaylist.getSongsObservable().flatMap(songs -> Observable.just(Operators.songsToAlbums(songs))).flatMapSingle(source -> Observable.fromIterable(source).sorted((a, b) -> ComparisonUtils.compareLong(b.songPlayCount, a.songPlayCount)).take(20).toList()).map(albums -> {
        if (!albums.isEmpty()) {
            List<ViewModel> viewModels = new ArrayList<>();
            SuggestedHeader recentlyAddedHeader = new SuggestedHeader(getString(R.string.recentlyadded), getString(R.string.suggested_recently_added_subtitle), Playlist.recentlyAddedPlaylist);
            SuggestedHeaderView recentlyAddedHeaderView = new SuggestedHeaderView(recentlyAddedHeader);
            recentlyAddedHeaderView.setClickListener(this);
            viewModels.add(recentlyAddedHeaderView);
            viewModels.addAll(Stream.of(albums).map(album -> {
                AlbumView albumView = new AlbumView(album, ViewType.ALBUM_CARD, requestManager);
                albumView.setClickListener(this);
                return albumView;
            }).toList());
            return viewModels;
        } else {
            return Collections.emptyList();
        }
    });
}
Also used : R(com.simplecity.amp_library.R) GridLayoutManager(android.support.v7.widget.GridLayoutManager) Bundle(android.os.Bundle) ViewModel(com.simplecityapps.recycler_adapter.model.ViewModel) SuggestedDividerDecoration(com.simplecity.amp_library.ui.views.SuggestedDividerDecoration) AndroidSchedulers(io.reactivex.android.schedulers.AndroidSchedulers) Song(com.simplecity.amp_library.model.Song) Optional(com.annimon.stream.Optional) RequestManager(com.bumptech.glide.RequestManager) MenuUtils(com.simplecity.amp_library.utils.MenuUtils) View(android.view.View) LogUtils(com.simplecity.amp_library.utils.LogUtils) Playlist(com.simplecity.amp_library.model.Playlist) PopupMenu(android.support.v7.widget.PopupMenu) ViewGroup(android.view.ViewGroup) SuggestedHeaderView(com.simplecity.amp_library.ui.modelviews.SuggestedHeaderView) MusicUtils(com.simplecity.amp_library.utils.MusicUtils) List(java.util.List) CompositeDisposable(io.reactivex.disposables.CompositeDisposable) Disposable(io.reactivex.disposables.Disposable) FragmentModule(com.simplecity.amp_library.dagger.module.FragmentModule) PermissionUtils(com.simplecity.amp_library.utils.PermissionUtils) Nullable(android.support.annotation.Nullable) Context(android.content.Context) SuggestedSongView(com.simplecity.amp_library.ui.modelviews.SuggestedSongView) Album(com.simplecity.amp_library.model.Album) Stream(com.annimon.stream.Stream) RecyclerListener(com.simplecityapps.recycler_adapter.recyclerview.RecyclerListener) EmptyView(com.simplecity.amp_library.ui.modelviews.EmptyView) ViewModelAdapter(com.simplecityapps.recycler_adapter.adapter.ViewModelAdapter) ViewType(com.simplecity.amp_library.ui.adapters.ViewType) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) SuppressLint(android.annotation.SuppressLint) SuggestedHeader(com.simplecity.amp_library.model.SuggestedHeader) Toast(android.widget.Toast) Observable(io.reactivex.Observable) UpgradeDialog(com.simplecity.amp_library.ui.dialog.UpgradeDialog) ShuttleUtils(com.simplecity.amp_library.utils.ShuttleUtils) LayoutInflater(android.view.LayoutInflater) AlbumView(com.simplecity.amp_library.ui.modelviews.AlbumView) TimeUnit(java.util.concurrent.TimeUnit) RecyclerView(android.support.v7.widget.RecyclerView) ShuttleApplication(com.simplecity.amp_library.ShuttleApplication) HorizontalRecyclerView(com.simplecity.amp_library.ui.modelviews.HorizontalRecyclerView) PlaylistDetailFragment(com.simplecity.amp_library.ui.detail.PlaylistDetailFragment) ComparisonUtils(com.simplecity.amp_library.utils.ComparisonUtils) DataManager(com.simplecity.amp_library.utils.DataManager) AlbumArtist(com.simplecity.amp_library.model.AlbumArtist) Operators(com.simplecity.amp_library.utils.Operators) Collections(java.util.Collections) SuggestedHeaderView(com.simplecity.amp_library.ui.modelviews.SuggestedHeaderView) AlbumView(com.simplecity.amp_library.ui.modelviews.AlbumView) ArrayList(java.util.ArrayList) ViewModel(com.simplecityapps.recycler_adapter.model.ViewModel) SuggestedHeader(com.simplecity.amp_library.model.SuggestedHeader)

Example 38 with Observable

use of io.reactivex.Observable in project Shuttle by timusus.

the class VoiceSearchActivity method searchAndPlaySongs.

private void searchAndPlaySongs() {
    DataManager.getInstance().getAlbumArtistsRelay().first(Collections.emptyList()).flatMapObservable(Observable::fromIterable).filter(albumArtist -> albumArtist.name.toLowerCase(Locale.getDefault()).contains(filterString.toLowerCase())).flatMapSingle(AlbumArtist::getSongsSingle).map(songs -> {
        Collections.sort(songs, (a, b) -> a.getAlbumArtist().compareTo(b.getAlbumArtist()));
        Collections.sort(songs, (a, b) -> a.getAlbum().compareTo(b.getAlbum()));
        Collections.sort(songs, (a, b) -> ComparisonUtils.compareInt(a.track, b.track));
        Collections.sort(songs, (a, b) -> ComparisonUtils.compareInt(a.discNumber, b.discNumber));
        return songs;
    });
    // Search for album-artists, albums & songs matching our filter. Then, create an Observable emitting List<Song> for each type of result.
    // Then we concat the results, and return the first one which is non-empty. Order is important here, we want album-artist first, if it's
    // available, then albums, then songs.
    Observable.concat(// If we have an album artist matching our query, then play the songs by that album artist
    DataManager.getInstance().getAlbumArtistsRelay().first(Collections.emptyList()).flatMapObservable(Observable::fromIterable).filter(albumArtist -> albumArtist.name.toLowerCase(Locale.getDefault()).contains(filterString.toLowerCase())).flatMapSingle(AlbumArtist::getSongsSingle).map(songs -> {
        Collections.sort(songs, (a, b) -> a.getAlbumArtist().compareTo(b.getAlbumArtist()));
        Collections.sort(songs, (a, b) -> a.getAlbum().compareTo(b.getAlbum()));
        Collections.sort(songs, (a, b) -> ComparisonUtils.compareInt(a.track, b.track));
        Collections.sort(songs, (a, b) -> ComparisonUtils.compareInt(a.discNumber, b.discNumber));
        return songs;
    }), // If we have an album matching our query, then play the songs from that album
    DataManager.getInstance().getAlbumsRelay().first(Collections.emptyList()).flatMapObservable(Observable::fromIterable).filter(album -> containsIgnoreCase(album.name, filterString) || containsIgnoreCase(album.name, filterString) || (Stream.of(album.artists).anyMatch(artist -> containsIgnoreCase(artist.name, filterString))) || containsIgnoreCase(album.albumArtistName, filterString)).flatMapSingle(Album::getSongsSingle).map(songs -> {
        Collections.sort(songs, (a, b) -> a.getAlbum().compareTo(b.getAlbum()));
        Collections.sort(songs, (a, b) -> ComparisonUtils.compareInt(a.track, b.track));
        Collections.sort(songs, (a, b) -> ComparisonUtils.compareInt(a.discNumber, b.discNumber));
        return songs;
    }), // If have a song, play that song, as well as others from the same album.
    DataManager.getInstance().getSongsRelay().first(Collections.emptyList()).flatMapObservable(Observable::fromIterable).filter(song -> containsIgnoreCase(song.name, filterString) || containsIgnoreCase(song.albumName, filterString) || containsIgnoreCase(song.artistName, filterString) || containsIgnoreCase(song.albumArtistName, filterString)).flatMapSingle(song -> song.getAlbum().getSongsSingle().map(songs -> {
        Collections.sort(songs, (a, b) -> ComparisonUtils.compareInt(a.track, b.track));
        Collections.sort(songs, (a, b) -> ComparisonUtils.compareInt(a.discNumber, b.discNumber));
        position = songs.indexOf(song);
        return songs;
    }))).filter(songs -> !songs.isEmpty()).firstOrError().observeOn(AndroidSchedulers.mainThread()).subscribe(songs -> {
        if (songs != null) {
            MusicUtils.playAll(songs, position, true, (String message) -> Toast.makeText(this, message, Toast.LENGTH_SHORT).show());
            startActivity(new Intent(this, MainActivity.class));
        }
        finish();
    }, error -> {
        LogUtils.logException(TAG, "Error attempting to playAll()", error);
        startActivity(new Intent(this, MainActivity.class));
        finish();
    });
}
Also used : LogUtils(com.simplecity.amp_library.utils.LogUtils) BaseActivity(com.simplecity.amp_library.ui.activities.BaseActivity) Bundle(android.os.Bundle) Album(com.simplecity.amp_library.model.Album) Stream(com.annimon.stream.Stream) ComponentName(android.content.ComponentName) MainActivity(com.simplecity.amp_library.ui.activities.MainActivity) Intent(android.content.Intent) AndroidSchedulers(io.reactivex.android.schedulers.AndroidSchedulers) IBinder(android.os.IBinder) MusicUtils(com.simplecity.amp_library.utils.MusicUtils) StringUtils.containsIgnoreCase(com.simplecity.amp_library.utils.StringUtils.containsIgnoreCase) Locale(java.util.Locale) Toast(android.widget.Toast) ComparisonUtils(com.simplecity.amp_library.utils.ComparisonUtils) DataManager(com.simplecity.amp_library.utils.DataManager) AlbumArtist(com.simplecity.amp_library.model.AlbumArtist) Observable(io.reactivex.Observable) SearchManager(android.app.SearchManager) Collections(java.util.Collections) Album(com.simplecity.amp_library.model.Album) Intent(android.content.Intent) MainActivity(com.simplecity.amp_library.ui.activities.MainActivity) Observable(io.reactivex.Observable) AlbumArtist(com.simplecity.amp_library.model.AlbumArtist)

Example 39 with Observable

use of io.reactivex.Observable in project Shuttle by timusus.

the class ArtworkDownloadService method onCreate.

@Override
public void onCreate() {
    super.onCreate();
    notificationHelper = new NotificationHelper(this);
    if (!ShuttleUtils.isOnline(false)) {
        Toast toast = Toast.makeText(this, getResources().getString(R.string.connection_unavailable), Toast.LENGTH_SHORT);
        toast.show();
        stopSelf();
        return;
    }
    notificationHelper.notify(NOTIFICATION_ID, getNotificationBuilder().build());
    Single<List<ArtworkProvider>> sharedItemsSingle = DataManager.getInstance().getAlbumArtistsRelay().first(Collections.emptyList()).<ArtworkProvider>flatMapObservable(Observable::fromIterable).mergeWith(DataManager.getInstance().getAlbumsRelay().first(Collections.emptyList()).flatMapObservable(Observable::fromIterable)).toList();
    disposables.add(sharedItemsSingle.observeOn(AndroidSchedulers.mainThread()).subscribe(list -> {
        max = list.size();
        updateProgress();
    }, error -> LogUtils.logException(TAG, "Error determining max", error)));
    disposables.add(sharedItemsSingle.flatMapObservable(Observable::fromIterable).flatMap(artworkProvider -> Observable.just(artworkProvider).map(artwork -> {
        FutureTarget<File> futureTarget = Glide.with(ArtworkDownloadService.this).using(new ArtworkModelLoader(true), InputStream.class).load(artwork).as(InputStream.class).downloadOnly(SimpleTarget.SIZE_ORIGINAL, SimpleTarget.SIZE_ORIGINAL);
        try {
            futureTarget.get(30, TimeUnit.SECONDS);
        } catch (InterruptedException | ExecutionException | TimeoutException e) {
            Log.e(TAG, "Error downloading artworkProvider: " + e);
        }
        Glide.clear(futureTarget);
        return artwork;
    })).subscribeOn(Schedulers.computation()).observeOn(AndroidSchedulers.mainThread()).subscribe(item -> updateProgress(), error -> LogUtils.logException(TAG, "Error downloading artwork", error)));
}
Also used : R(com.simplecity.amp_library.R) TimeoutException(java.util.concurrent.TimeoutException) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) NotificationHelper(com.simplecity.amp_library.notifications.NotificationHelper) Single(io.reactivex.Single) AndroidSchedulers(io.reactivex.android.schedulers.AndroidSchedulers) IBinder(android.os.IBinder) FutureTarget(com.bumptech.glide.request.FutureTarget) Toast(android.widget.Toast) Observable(io.reactivex.Observable) Schedulers(io.reactivex.schedulers.Schedulers) ShuttleUtils(com.simplecity.amp_library.utils.ShuttleUtils) Log(android.util.Log) ArtworkModelLoader(com.simplecity.amp_library.glide.loader.ArtworkModelLoader) SimpleTarget(com.bumptech.glide.request.target.SimpleTarget) LogUtils(com.simplecity.amp_library.utils.LogUtils) ComponentName(android.content.ComponentName) Service(android.app.Service) ArtworkProvider(com.simplecity.amp_library.model.ArtworkProvider) File(java.io.File) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) CompositeDisposable(io.reactivex.disposables.CompositeDisposable) Glide(com.bumptech.glide.Glide) NotificationCompat(android.support.v4.app.NotificationCompat) DataManager(com.simplecity.amp_library.utils.DataManager) Nullable(android.support.annotation.Nullable) Collections(java.util.Collections) InputStream(java.io.InputStream) ArtworkModelLoader(com.simplecity.amp_library.glide.loader.ArtworkModelLoader) FutureTarget(com.bumptech.glide.request.FutureTarget) Toast(android.widget.Toast) NotificationHelper(com.simplecity.amp_library.notifications.NotificationHelper) ArtworkProvider(com.simplecity.amp_library.model.ArtworkProvider) List(java.util.List) Observable(io.reactivex.Observable)

Example 40 with Observable

use of io.reactivex.Observable in project Offer by woshiyizhijiao.

the class RxJavaActivity method zip2.

/**
 * 上游两个管道的其中一个在无线发送事件,而另一个管道只发送一个,最终导致oom
 */
public void zip2(View v) {
    Observable observable1 = Observable.create(new ObservableOnSubscribe<Integer>() {

        @Override
        public void subscribe(ObservableEmitter<Integer> emitter) throws Exception {
            for (int x = 0; ; x++) {
                emitter.onNext(1);
            }
        }
    }).subscribeOn(Schedulers.io());
    Observable<String> observable2 = Observable.create(new ObservableOnSubscribe<String>() {

        @Override
        public void subscribe(ObservableEmitter<String> emitter) throws Exception {
            emitter.onNext("第二个管道");
        }
    }).subscribeOn(Schedulers.io());
    Observable.zip(observable1, observable2, new BiFunction<Integer, String, String>() {

        /**
         * Calculate a value based on the input values.
         *
         * @param integer the first value
         * @param s       the second value
         * @return the result value
         * @throws Exception on error
         */
        @Override
        public String apply(Integer integer, String s) throws Exception {
            return integer + s;
        }
    }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer() {

        @Override
        public void onSubscribe(Disposable d) {
        }

        @Override
        public void onNext(Object value) {
            LogUtils.e("onNext" + value);
        }

        @Override
        public void onError(Throwable e) {
        }

        @Override
        public void onComplete() {
        }
    });
}
Also used : Disposable(io.reactivex.disposables.Disposable) ObservableOnSubscribe(io.reactivex.ObservableOnSubscribe) Observable(io.reactivex.Observable) Observer(io.reactivex.Observer) ObservableEmitter(io.reactivex.ObservableEmitter)

Aggregations

Observable (io.reactivex.Observable)88 InOrder (org.mockito.InOrder)27 Test (org.junit.Test)25 TestException (io.reactivex.exceptions.TestException)24 List (java.util.List)17 Observer (io.reactivex.Observer)12 Function (io.reactivex.functions.Function)11 ArrayList (java.util.ArrayList)11 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)11 AndroidSchedulers (io.reactivex.android.schedulers.AndroidSchedulers)10 TestObserver (io.reactivex.observers.TestObserver)10 Bundle (android.os.Bundle)8 Nullable (android.support.annotation.Nullable)8 TimeUnit (java.util.concurrent.TimeUnit)8 LayoutInflater (android.view.LayoutInflater)7 View (android.view.View)7 ViewGroup (android.view.ViewGroup)7 TypeReference (com.fasterxml.jackson.core.type.TypeReference)7 JsonObject (io.vertx.core.json.JsonObject)7 HttpResponse (io.vertx.reactivex.ext.web.client.HttpResponse)7