rx.subjects.BehaviorSubject Java Examples

The following examples show how to use rx.subjects.BehaviorSubject. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LocalPlaylistStore.java    From Jockey with Apache License 2.0 6 votes vote down vote up
@Override
public Observable<Boolean> refresh() {
    if (mPlaylists == null) {
        return Observable.just(true);
    }

    mLoadingState.onNext(true);

    BehaviorSubject<Boolean> result = BehaviorSubject.create();

    MediaStoreUtil.promptPermission(mContext)
            .observeOn(Schedulers.io())
            .map(granted -> {
                if (granted && mPlaylists != null) {
                    mPlaylists.onNext(getAllPlaylists());
                    mPlaylistContents.clear();
                }
                mLoadingState.onNext(false);
                return granted;
            })
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(result);

    return result;
}
 
Example #2
Source File: BackupRequestStrategyTest.java    From ocelli with Apache License 2.0 6 votes vote down vote up
@Test
public void bothDelayed() {
    BehaviorSubject<List<Observable<Integer>>> subject = BehaviorSubject.create(Arrays.asList(
            Observable.just(1).delaySubscription(2, TimeUnit.SECONDS, scheduler),
            Observable.just(2).delaySubscription(2, TimeUnit.SECONDS, scheduler),
            Observable.just(3)));
    
    LoadBalancer<Observable<Integer>> lb = LoadBalancer.fromSnapshotSource(subject).build(RoundRobinLoadBalancer.<Observable<Integer>>create(-1));
    
    final AtomicInteger lbCounter = new AtomicInteger();
    final AtomicReference<String> result = new AtomicReference<String>();
    
    lb  .toObservable()
        .doOnNext(RxUtil.increment(lbCounter))
        .flatMap(Operation)
        .compose(strategy)
        .doOnNext(RxUtil.set(result))
        .subscribe();

    scheduler.advanceTimeBy(1, TimeUnit.SECONDS);
    scheduler.advanceTimeBy(1, TimeUnit.SECONDS);
    scheduler.advanceTimeBy(3, TimeUnit.SECONDS);
    
    Assert.assertEquals(2, lbCounter.get());
    Assert.assertEquals("1", result.get());
}
 
Example #3
Source File: LocalPlaylistStore.java    From Jockey with Apache License 2.0 6 votes vote down vote up
private Observable<List<Song>> getAutoPlaylistSongs(AutoPlaylist playlist) {
    BehaviorSubject<List<Song>> subject;

    if (mPlaylistContents.containsKey(playlist)) {
        subject = mPlaylistContents.get(playlist);
    } else {
        subject = BehaviorSubject.create();
        mPlaylistContents.put(playlist, subject);

        playlist.generatePlaylist(mMusicStore, this, mPlayCountStore)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subject::onNext, subject::onError);

        subject.observeOn(Schedulers.io())
                .subscribe(contents -> {
                    MediaStoreUtil.editPlaylist(mContext, playlist, contents);
                }, throwable -> {
                    Timber.e(throwable, "Failed to save playlist contents");
                });
    }

    return subject.asObservable();
}
 
Example #4
Source File: LocalPlaylistStore.java    From Jockey with Apache License 2.0 6 votes vote down vote up
@Override
public Observable<List<Playlist>> getPlaylists() {
    if (mPlaylists == null) {
        mPlaylists = BehaviorSubject.create();
        mLoadingState.onNext(true);

        MediaStoreUtil.getPermission(mContext)
                .observeOn(Schedulers.io())
                .subscribe(granted -> {
                    if (granted) {
                        mPlaylists.onNext(getAllPlaylists());
                    } else {
                        mPlaylists.onNext(Collections.emptyList());
                    }
                    mLoadingState.onNext(false);
                }, throwable -> {
                    Timber.e(throwable, "Failed to query MediaStore for playlists");
                });
    }
    return mPlaylists.asObservable().observeOn(AndroidSchedulers.mainThread());
}
 
Example #5
Source File: ServicePlayerController.java    From Jockey with Apache License 2.0 6 votes vote down vote up
@Override
public Observable<Bitmap> getArtwork() {
    if (mArtwork == null) {
        mArtwork = BehaviorSubject.create(BitmapFactory.decodeResource(
                mContext.getResources(), R.drawable.art_default_xl));

        getNowPlaying()
                .observeOn(Schedulers.io())
                .flatMap((Song song) -> {
                    return Util.fetchArtwork(mContext, song);
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(mArtwork::onNext, throwable -> {
                    Timber.e(throwable, "Failed to fetch artwork");
                    mArtwork.onNext(null);
                });
    }

    return mArtwork;
}
 
Example #6
Source File: SearchViewModel.java    From Jockey with Apache License 2.0 6 votes vote down vote up
public SearchViewModel(Context context, FragmentManager fragmentManager,
                       PlayerController playerController, MusicStore musicStore,
                       PlaylistStore playlistStore,
                       @Nullable OnSongSelectedListener songSelectedListener,
                       String initialQuery) {

    super(context);
    mFragmentManager = fragmentManager;
    mPlayerController = playerController;
    mMusicStore = musicStore;
    mPlaylistStore = playlistStore;

    mQuerySubject = BehaviorSubject.create(initialQuery);

    createAdapter(songSelectedListener);
    observeSearchQuery();
}
 
Example #7
Source File: WebSocketService.java    From client-sdk-java with Apache License 2.0 6 votes vote down vote up
@Override
public <T extends Notification<?>> Observable<T> subscribe(
        Request request,
        String unsubscribeMethod,
        Class<T> responseType) {
    // We can't use usual Observer since we can call "onError"
    // before first client is subscribed and we need to
    // preserve it
    BehaviorSubject<T> subject = BehaviorSubject.create();

    // We need to subscribe synchronously, since if we return
    // an Observable to a client before we got a reply
    // a client can unsubscribe before we know a subscription
    // id and this can cause a race condition
    subscribeToEventsStream(request, subject, responseType);

    return subject
            .doOnUnsubscribe(() -> closeSubscription(subject, unsubscribeMethod));

}
 
Example #8
Source File: WorkerExecutionOperationsNetworkStage.java    From mantis with Apache License 2.0 6 votes vote down vote up
/**
 * Deprecated.
 *
 * @param selfSchedulingInfo
 * @param jobId
 * @param stageNum
 *
 * @return
 */
private BehaviorSubject<Boolean> createPrevStageCompletedObservable(Observable<JobSchedulingInfo> selfSchedulingInfo, String jobId, final int stageNum) {
    BehaviorSubject<Boolean> s = BehaviorSubject.create(false);

    //		if(stageNum>1) {
    //			selfSchedulingInfo
    //					.map(schedulingInfo -> {
    //						final Map<Integer, WorkerAssignments> workerAssignmentsMap = schedulingInfo.getWorkerAssignments();
    //						if (workerAssignmentsMap == null)
    //							return false;
    //						final WorkerAssignments workerAssignments = workerAssignmentsMap.get(stageNum - 1);
    //						return workerAssignments != null && workerAssignments.getActiveWorkers() == 0;
    //					})
    //					.subscribe(s);
    //		}
    return s;
}
 
Example #9
Source File: ZookeeperMasterMonitor.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
public ZookeeperMasterMonitor(ZookeeperPaths zkPaths,
                              CuratorFramework curator,
                              MasterDescription initValue,
                              TitusRuntime titusRuntime,
                              Scheduler scheduler) {
    this.curator = curator;
    this.titusRuntime = titusRuntime;

    this.leaderPath = zkPaths.getLeaderAnnouncementPath();
    this.leaderSubject = BehaviorSubject.create(initValue).toSerialized();
    this.leaderMonitor = new NodeCache(curator, leaderPath);
    this.latestLeader.set(initValue);

    this.allMastersPath = zkPaths.getAllMastersPath();
    this.masterMonitor = new TreeCache(curator, allMastersPath);

    this.refreshOwnMasterInstanceSubscriber = ObservableExt.schedule(
            ZookeeperConstants.METRICS_ROOT + "masterMonitor.ownInstanceRefreshScheduler",
            titusRuntime.getRegistry(),
            "reRegisterOwnMasterInstanceInZookeeper",
            registerOwnMasterInstance(() -> ownMasterInstance),
            OWN_MASTER_REFRESH_INTERVAL_MS, OWN_MASTER_REFRESH_INTERVAL_MS, TimeUnit.MILLISECONDS,
            scheduler
    ).subscribe();
}
 
Example #10
Source File: MediaStoreUtil.java    From Jockey with Apache License 2.0 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.M)
public static Observable<Boolean> promptPermission(Context context) {
    if (sPermissionObservable == null) {
        sPermissionObservable = BehaviorSubject.create();
    }

    if (hasPermission(context)) {
        if (!sPermissionObservable.hasValue() || !sPermissionObservable.getValue()) {
            sPermissionObservable.onNext(true);
        }
        return getPermissionObservable();
    }

    RxPermissions.getInstance(context).request(READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE)
            .subscribe(sPermissionObservable::onNext, throwable -> {
                Timber.i(throwable, "Failed to get storage permission");
            });

    return getPermissionObservable();
}
 
Example #11
Source File: LocalMusicStore.java    From Jockey with Apache License 2.0 6 votes vote down vote up
@Override
public Observable<List<Genre>> getGenres() {
    if (mGenres == null) {
        mGenres = BehaviorSubject.create();
        mGenreLoadingState.onNext(true);

        MediaStoreUtil.getPermission(mContext)
                .observeOn(Schedulers.io())
                .subscribe(granted -> {
                    if (granted) {
                        mGenres.onNext(getAllGenres());
                    } else {
                        mGenres.onNext(Collections.emptyList());
                    }
                    mGenreLoadingState.onNext(false);
                }, throwable -> {
                    Timber.e(throwable, "Failed to query MediaStore for genres");
                });
    }
    return mGenres.asObservable().observeOn(AndroidSchedulers.mainThread());
}
 
Example #12
Source File: ChoiceOfTwoLoadBalancerTest.java    From ocelli with Apache License 2.0 6 votes vote down vote up
@Test
public void testMany() {
    BehaviorSubject<List<Integer>> source = BehaviorSubject.create();
    LoadBalancer<Integer> lb = LoadBalancer.fromSnapshotSource(source).build(ChoiceOfTwoLoadBalancer.create(COMPARATOR));
    
    source.onNext(Lists.newArrayList(0,1,2,3,4,5,6,7,8,9));
    
    AtomicIntegerArray counts = new AtomicIntegerArray(10);
    
    for (int i = 0; i < 100000; i++) {
        counts.incrementAndGet(lb.next());
    }
    Double[] pct = new Double[counts.length()];
    for (int i = 0; i < counts.length(); i++) {
        pct[i] = counts.get(i)/100000.0;
    }
    
    for (int i = 1; i < counts.length(); i++) {
        Assert.assertTrue(counts.get(i) > counts.get(i-1));
    }
}
 
Example #13
Source File: BackupRequestStrategyTest.java    From ocelli with Apache License 2.0 6 votes vote down vote up
@Test
public void firstNeverSecondSucceeds() {
    BehaviorSubject<List<Observable<Integer>>> subject = BehaviorSubject.create(Arrays.asList(
            Observable.<Integer>never(),
            Observable.just(2),
            Observable.just(3)));

    LoadBalancer<Observable<Integer>> lb = LoadBalancer.fromSnapshotSource(subject).build(RoundRobinLoadBalancer.<Observable<Integer>>create(-1));
    
    final AtomicInteger lbCounter = new AtomicInteger();
    final AtomicReference<String> result = new AtomicReference<String>();
    
    lb  .toObservable()
        .doOnNext(RxUtil.increment(lbCounter))
        .flatMap(Operation)
        .compose(strategy)
        .doOnNext(RxUtil.set(result))
        .subscribe();

    scheduler.advanceTimeBy(2, TimeUnit.SECONDS);
    scheduler.advanceTimeBy(1, TimeUnit.SECONDS);
    
    Assert.assertEquals("2", result.get());
    Assert.assertEquals(2, lbCounter.get());
}
 
Example #14
Source File: MusicBrowserViewModel.java    From Jockey with Apache License 2.0 6 votes vote down vote up
public MusicBrowserViewModel(Context context, File startingDirectory,
                             @NonNull OnSongFileSelectedListener songSelectionListener) {
    super(context);
    mSelectionListener = songSelectionListener;
    mHistory = new Stack<>();
    mBreadCrumbs = Collections.emptyList();
    mDirectoryObservable = BehaviorSubject.create(startingDirectory);

    mAdapter = new HeterogeneousAdapter();
    mFolderSection = new FolderSection(Collections.emptyList(), this::onClickFolder);
    mThumbnailLoader = new ThumbnailLoader(context);
    mFileSection = new FileSection(Collections.emptyList(), this::onClickSong, mThumbnailLoader);
    mAdapter.addSection(mFolderSection);
    mAdapter.addSection(mFileSection);
    mAdapter.setEmptyState(new FileBrowserEmptyState(context, this::onRefreshFromEmptyState));
    mAdapter.setHasStableIds(true);

    setDirectory(startingDirectory);
}
 
Example #15
Source File: BackupRequestStrategyTest.java    From ocelli with Apache License 2.0 6 votes vote down vote up
@Test
public void firstSucceedsSecondFailsAfterBackupStarted() {
    BehaviorSubject<List<Observable<Integer>>> subject = BehaviorSubject.create(Arrays.asList(
            Observable.just(1).delaySubscription(2, TimeUnit.SECONDS, scheduler),
            Observable.<Integer>error(new Exception("2")),
            Observable.just(3)));
    
    LoadBalancer<Observable<Integer>> lb = LoadBalancer.fromSnapshotSource(subject).build(RoundRobinLoadBalancer.<Observable<Integer>>create(-1));
    
    final AtomicInteger lbCounter = new AtomicInteger();
    final AtomicReference<String> result = new AtomicReference<String>();
    
    lb  .toObservable()
        .doOnNext(RxUtil.increment(lbCounter))
        .flatMap(Operation)
        .compose(strategy)
        .doOnNext(RxUtil.set(result))
        .subscribe();

    scheduler.advanceTimeBy(1, TimeUnit.SECONDS);
    scheduler.advanceTimeBy(1, TimeUnit.SECONDS);
    scheduler.advanceTimeBy(1, TimeUnit.SECONDS);
    
    Assert.assertEquals("1", result.get());
    Assert.assertEquals(2, lbCounter.get());
}
 
Example #16
Source File: AwaitableEventSubscriberDecoratorTest.java    From mesos-rxjava with Apache License 2.0 6 votes vote down vote up
@Test
public void awaitEventWorks() throws Exception {
    final TestSubscriber<String> testSubscriber = new TestSubscriber<>();
    final AwaitableEventSubscriberDecorator<String> sub = new AwaitableEventSubscriberDecorator<>(testSubscriber);

    final BehaviorSubject<String> subject = BehaviorSubject.create();

    final Subscription subscription = subject.subscribe(sub);

    async.run(() -> {
        subject.onNext("hello");
        subject.onNext("world");
        subject.onNext("!");
        subject.onCompleted();
    });

    sub.awaitEvent(Integer.MAX_VALUE);
    testSubscriber.assertValues("hello", "world", "!");
    testSubscriber.assertCompleted();
    testSubscriber.assertNoErrors();
    subscription.unsubscribe();
}
 
Example #17
Source File: AwaitableEventSubscriberDecoratorTest.java    From mesos-rxjava with Apache License 2.0 6 votes vote down vote up
@Test
public void awaitEventWorks_onError() throws Exception {
    final TestSubscriber<String> testSubscriber = new TestSubscriber<>();
    final AwaitableEventSubscriberDecorator<String> sub = new AwaitableEventSubscriberDecorator<>(testSubscriber);

    final BehaviorSubject<String> subject = BehaviorSubject.create();

    final Subscription subscription = subject.subscribe(sub);

    final RuntimeException e = new RuntimeException("doesn't matter");
    async.run(() -> subject.onError(e));

    sub.awaitEvent();
    testSubscriber.assertNoValues();
    testSubscriber.assertError(e);
    subscription.unsubscribe();
}
 
Example #18
Source File: ComposeMonitor.java    From haven-platform with Apache License 2.0 6 votes vote down vote up
public ComposeMonitor(DockerService dockerService, String fileName) {
    this.monitor = BehaviorSubject.create();
    this.dockerService = dockerService;
    this.fileName = fileName;
    this.observer = Observers.create(t -> {
        List<String> containerIds = getContainerIds();
        containerIds.forEach(s -> {
            ContainerDetails details = dockerService.getContainer(s);
            log.debug("get container {}", details);
            if (checkContainer(details)) {
                log.error("Container crashed {}", details);
                monitor.onNext(ResultCode.ERROR);
                monitor.onCompleted();
                return;
            }
        });
    });
}
 
Example #19
Source File: DemoMusicStore.java    From Jockey with Apache License 2.0 5 votes vote down vote up
@Override
public Observable<List<Album>> getAlbums() {
    if (mAlbums == null) {
        BehaviorSubject<List<Album>> subject = BehaviorSubject.create();

        Observable.fromCallable(() -> parseJson(ALBUMS_FILENAME, Album[].class))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subject::onNext, subject::onError);

        mAlbums = subject.asObservable();
    }

    return mAlbums;
}
 
Example #20
Source File: ChoiceOfTwoLoadBalancerTest.java    From ocelli with Apache License 2.0 5 votes vote down vote up
@Test
public void testTwo() {
    BehaviorSubject<List<Integer>> source = BehaviorSubject.create();
    LoadBalancer<Integer> lb = LoadBalancer.fromSnapshotSource(source).build(ChoiceOfTwoLoadBalancer.create(COMPARATOR));
    
    source.onNext(Lists.newArrayList(0,1));
    
    AtomicIntegerArray counts = new AtomicIntegerArray(2);
    
    for (int i = 0; i < 100; i++) {
        counts.incrementAndGet(lb.next());
    }
    Assert.assertEquals(counts.get(0), 0);
    Assert.assertEquals(counts.get(1), 100);
}
 
Example #21
Source File: DemoMusicStore.java    From Jockey with Apache License 2.0 5 votes vote down vote up
@Override
public Observable<List<Artist>> getArtists() {
    if (mArtists == null) {
        BehaviorSubject<List<Artist>> subject = BehaviorSubject.create();

        Observable.fromCallable(() -> parseJson(ARTISTS_FILENAME, Artist[].class))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subject::onNext, subject::onError);

        mArtists = subject.asObservable();
    }

    return mArtists;
}
 
Example #22
Source File: LocalPlaylistStore.java    From Jockey with Apache License 2.0 5 votes vote down vote up
public LocalPlaylistStore(Context context, MusicStore musicStore,
                          PlayCountStore playCountStore) {
    mContext = context;
    mMusicStore = musicStore;
    mPlayCountStore = playCountStore;
    mPlaylistContents = new ArrayMap<>();
    mLoadingState = BehaviorSubject.create(false);

    MediaStoreUtil.waitForPermission()
            .subscribe(permission -> bindRefreshListener(), throwable -> {
                Timber.e(throwable, "Failed to bind refresh listener");
            });
}
 
Example #23
Source File: EndpointFactoryMock.java    From couchbase-jvm-core with Apache License 2.0 5 votes vote down vote up
public void onDisconnectTransition(final Func1<Endpoint, LifecycleState> action) {
    onCreate(new Action2<Endpoint, BehaviorSubject<LifecycleState>>() {
        @Override
        public void call(final Endpoint endpoint, final BehaviorSubject<LifecycleState> states) {
            when(endpoint.disconnect()).then(new Answer<Observable<LifecycleState>>() {
                @Override
                public Observable<LifecycleState> answer(InvocationOnMock invocation) throws Throwable {
                    LifecycleState state = action.call(endpoint);
                    states.onNext(state);
                    return Observable.just(state);
                }
            });
        }
    });
}
 
Example #24
Source File: ServicePlayerController.java    From Jockey with Apache License 2.0 5 votes vote down vote up
public ServicePlayerController(Context context, PreferenceStore preferenceStore,
            PlaybackPersistenceManager persistenceManager) {
    mContext = context;
    mPreferenceStore = preferenceStore;
    mPersistenceManager = persistenceManager;
    mConnection = new PlayerServiceConnection();
    mRequestThread = new HandlerThread("ServiceExecutor");
    mMediaSessionToken = BehaviorSubject.create();
    mRequestQueue = new ObservableQueue<>();
    mActiveBindings = new HashSet<>();

    mShuffleMode.setValue(preferenceStore.isShuffled());
    mRepeatMode.setValue(preferenceStore.getRepeatMode());

    mShuffleSeedGenerator = new Random();
    mMainHandler = new Handler(Looper.getMainLooper());
    mRequestThread.start();

    isPlaying().subscribe(
            isPlaying -> {
                if (isPlaying) {
                    startCurrentPositionClock();
                } else {
                    stopCurrentPositionClock();
                }
            }, throwable -> {
                Timber.e(throwable, "Failed to update current position clock");
            });
}
 
Example #25
Source File: LocalMusicStore.java    From Jockey with Apache License 2.0 5 votes vote down vote up
public LocalMusicStore(Context context, PreferenceStore preferenceStore) {
    mContext = context;
    mPreferenceStore = preferenceStore;

    mSongLoadingState = BehaviorSubject.create(false);
    mAlbumLoadingState = BehaviorSubject.create(false);
    mArtistLoadingState = BehaviorSubject.create(false);
    mGenreLoadingState = BehaviorSubject.create(false);

    MediaStoreUtil.waitForPermission()
            .subscribe(permission -> bindRefreshListener(), throwable -> {
                Timber.e(throwable, "Failed to bind refresh listener");
            });
}
 
Example #26
Source File: QueueSection.java    From Jockey with Apache License 2.0 5 votes vote down vote up
public QueueSection(List<Song> data, FragmentManager fragmentManager,
                    MusicStore musicStore, PlaylistStore playlistStore,
                    PlayerController playerController,
                    @Nullable OnSongSelectedListener songSelectedListener) {
    super(data);
    mFragmentManager = fragmentManager;

    mMusicStore = musicStore;
    mPlaylistStore = playlistStore;
    mPlayerController = playerController;
    mSongListener = songSelectedListener;
    mCurrentIndex = BehaviorSubject.create();
}
 
Example #27
Source File: SleepySimulationTest.java    From mesos-rxjava with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    subject = BehaviorSubject.create();
    sim = new MesosServerSimulation<>(
        subject,
        ProtobufMessageCodecs.SCHEDULER_EVENT,
        ProtobufMessageCodecs.SCHEDULER_CALL,
        (e) -> e.getType() == Protos.Call.Type.SUBSCRIBE
    );
    final int serverPort = sim.start();
    uri = URI.create(String.format("http://localhost:%d/api/v1/scheduler", serverPort));
}
 
Example #28
Source File: ObservableGithubRepos.java    From RxRestSample with Apache License 2.0 5 votes vote down vote up
public Observable<String> updateRepo(String userName) {
    BehaviorSubject<String> requestSubject = BehaviorSubject.create();

    Observable<List<Repo>> observable = mClient.getRepos(userName);
    observable.subscribeOn(Schedulers.io())
              .observeOn(Schedulers.io())
              .subscribe(l -> {
                                mDatabase.insertRepoList(l);
                                requestSubject.onNext(userName);},
                         e -> requestSubject.onError(e),
                         () -> requestSubject.onCompleted());
    return requestSubject.asObservable();
}
 
Example #29
Source File: WorkerExecutionOperationsNetworkStageTest.java    From mantis with Apache License 2.0 5 votes vote down vote up
Observable<Long> getObs4() {
    BehaviorSubject<Long> o = BehaviorSubject.create();
    Observable.interval(1, TimeUnit.SECONDS).doOnNext((e) -> {
        System.out.println("Minted " + e);
    }).doOnSubscribe(() -> {
        System.out.println("Subscribed111" + System.currentTimeMillis());
    }).doOnUnsubscribe(() -> {
        System.out.println("UnSubscribed111" + System.currentTimeMillis());
    })
            .subscribe(o);

    return o;

}
 
Example #30
Source File: LocalMusicStore.java    From Jockey with Apache License 2.0 5 votes vote down vote up
@Override
public Observable<List<Artist>> getArtists() {
    if (mArtists == null) {
        mArtists = BehaviorSubject.create();
        mArtistLoadingState.onNext(true);

        MediaStoreUtil.getPermission(mContext)
                .flatMap(granted -> {
                    if (noDirectoryFilters()) {
                        return Observable.just(granted);
                    } else {
                        return getSongs().map((List<Song> songs) -> granted);
                    }
                })
                .observeOn(Schedulers.io())
                .subscribe(granted -> {
                    if (granted) {
                        mArtists.onNext(getAllArtists());
                    } else {
                        mArtists.onNext(Collections.emptyList());
                    }
                    mArtistLoadingState.onNext(false);
                }, throwable -> {
                    Timber.e(throwable, "Failed to query MediaStore for artists");
                });
    }
    return mArtists.asObservable().observeOn(AndroidSchedulers.mainThread());
}