Java Code Examples for rx.subjects.BehaviorSubject#create()

The following examples show how to use rx.subjects.BehaviorSubject#create() . 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: 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 2
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 3
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 4
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 5
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 6
Source File: StageExecutorsTest.java    From mantis with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings( {"rawtypes", "unchecked"})
@Test
public void testExecuteSource() {

    TestJob provider = new TestJob();
    Job<Integer> job = provider.getJobInstance();

    List<StageConfig<?, ?>> stages = job.getStages();
    PortSelectorWithinRange portSelector = new PortSelectorWithinRange(8000, 9000);
    int serverPort = portSelector.acquirePort();

    WorkerPublisher producer = new WorkerPublisherRemoteObservable(serverPort, null,
            Observable.just(1), null);
    // execute source
    BehaviorSubject<Integer> workersInStageOneObservable = BehaviorSubject.create(1);
    StageExecutors.executeSource(0, job.getSource(), stages.get(0), producer,
            new Context(), workersInStageOneObservable);

    Iterator<Integer> iter = RemoteObservable.connect(new ConnectToObservable.Builder<Integer>()
            .host("localhost")
            .slotId("0")
            .port(serverPort)
            .decoder(Codecs.integer())
            .build())
            .getObservable()
            .toBlocking()
            .getIterator();

    // verify numbers are doubled
    Assert.assertEquals(0, iter.next().intValue());
    Assert.assertEquals(1, iter.next().intValue());
    Assert.assertEquals(4, iter.next().intValue());
    Assert.assertEquals(9, iter.next().intValue());
}
 
Example 7
Source File: LocalMusicStore.java    From Jockey with Apache License 2.0 5 votes vote down vote up
@Override
public Observable<Boolean> refresh() {
    mSongLoadingState.onNext(true);
    mArtistLoadingState.onNext(true);
    mAlbumLoadingState.onNext(true);
    mGenreLoadingState.onNext(true);

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

    MediaStoreUtil.promptPermission(mContext)
            .observeOn(Schedulers.io())
            .map(granted -> {
                if (granted) {
                    if (mSongs != null) {
                        mSongs.onNext(getAllSongs());
                    }
                    if (mArtists != null) {
                        mArtists.onNext(getAllArtists());
                    }
                    if (mAlbums != null) {
                        mAlbums.onNext(getAllAlbums());
                    }
                    if (mGenres != null) {
                        mGenres.onNext(getAllGenres());
                    }
                }
                mSongLoadingState.onNext(false);
                mArtistLoadingState.onNext(false);
                mAlbumLoadingState.onNext(false);
                mGenreLoadingState.onNext(false);
                return granted;
            })
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(result);

    return result.asObservable();
}
 
Example 8
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());
}
 
Example 9
Source File: MediaStoreUtil.java    From Jockey with Apache License 2.0 5 votes vote down vote up
public static Observable<Boolean> waitForPermission() {
    if (sPermissionObservable == null) {
        sPermissionObservable = BehaviorSubject.create();
    }

    return getPermissionObservable().filter(hasPermission -> hasPermission).take(1);
}
 
Example 10
Source File: MediaStoreUtil.java    From Jockey with Apache License 2.0 5 votes vote down vote up
public static Observable<Boolean> getContentObserver(Context context, Uri uri) {
    BehaviorSubject<Boolean> observer;

    if (!sContentObservers.containsKey(uri)) {
        observer = BehaviorSubject.create();
        sContentObservers.put(uri, observer);
        sSelfPendingUpdates.put(uri, 0);

        context.getContentResolver().registerContentObserver(uri, true,
                new ContentObserver(null) {
                    @Override
                    public void onChange(boolean selfChange) {
                        observer.onNext(selfChange);
                    }
                });
    } else {
        observer = sContentObservers.get(uri);
    }

    return observer.filter(selfChange -> {
        int pendingUpdates = sSelfPendingUpdates.get(uri);

        if (pendingUpdates > 0) {
            pendingUpdates--;
            sSelfPendingUpdates.put(uri, pendingUpdates);
            return false;
        } else {
            return true;
        }
    });
}
 
Example 11
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 12
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 13
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 14
Source File: ChoiceOfTwoLoadBalancerTest.java    From ocelli with Apache License 2.0 5 votes vote down vote up
@Test
public void testOne() {
    BehaviorSubject<List<Integer>> source = BehaviorSubject.create();
    LoadBalancer<Integer> lb = LoadBalancer.fromSnapshotSource(source).build(ChoiceOfTwoLoadBalancer.create(COMPARATOR));
    
    source.onNext(Lists.newArrayList(0));

    for (int i = 0; i < 100; i++) {
        Assert.assertEquals(0, (int)lb.next());
    }
}
 
Example 15
Source File: DemoPlaylistStore.java    From Jockey with Apache License 2.0 5 votes vote down vote up
@Override
public Observable<List<Playlist>> getPlaylists() {
    if (mPlaylists == null) {
        BehaviorSubject<List<Playlist>> subject = BehaviorSubject.create();
        Observable.fromCallable(this::readPlaylists)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subject);

        mPlaylists = subject;
    }

    return mPlaylists;
}
 
Example 16
Source File: ComposeMonitor.java    From docker-compose-executor with Apache License 2.0 4 votes vote down vote up
public ComposeMonitor() {
    monitor = BehaviorSubject.create();
}
 
Example 17
Source File: DeliverReplayTest.java    From FlowGeek with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void testPagingCapabilities() {
    PublishSubject<Object> view = PublishSubject.create();
    BehaviorSubject<Integer> nextPageRequests = BehaviorSubject.create();
    final TestObserver<Delivery<Object, String>> testObserver = new TestObserver<>();

    nextPageRequests
        .concatMap(new Func1<Integer, Observable<Integer>>() {
            @Override
            public Observable<Integer> call(Integer targetPage) {
                return targetPage <= requestedPageCount ?
                    Observable.<Integer>never() :
                    Observable.range(requestedPageCount, targetPage - requestedPageCount);
            }
        })
        .doOnNext(new Action1<Integer>() {
            @Override
            public void call(Integer it) {
                requestedPageCount = it + 1;
            }
        })
        .startWith(Observable.range(0, requestedPageCount))
        .concatMap(new Func1<Integer, Observable<String>>() {
            @Override
            public Observable<String> call(final Integer page) {
                return requestPage(page, PAGE_SIZE);
            }
        })
        .compose(new DeliverReplay<Object, String>(view))
        .subscribe(testObserver);

    ArrayList<Delivery<Object, String>> onNext = new ArrayList<>();

    testObserver.assertReceivedOnNext(onNext);

    view.onNext(999);
    addOnNext(onNext, 999, 0, 1, 2);

    testObserver.assertReceivedOnNext(onNext);

    nextPageRequests.onNext(2);
    addOnNext(onNext, 999, 3, 4, 5);

    testObserver.assertReceivedOnNext(onNext);

    view.onNext(null);

    assertEquals(0, testObserver.getOnCompletedEvents().size());
    testObserver.assertReceivedOnNext(onNext);

    nextPageRequests.onNext(3);

    assertEquals(0, testObserver.getOnCompletedEvents().size());
    testObserver.assertReceivedOnNext(onNext);

    view.onNext(9999);
    addOnNext(onNext, 9999, 0, 1, 2, 3, 4, 5, 6, 7, 8);

    assertEquals(0, testObserver.getOnCompletedEvents().size());
    testObserver.assertReceivedOnNext(onNext);
}
 
Example 18
Source File: SettingsProducer.java    From android with GNU General Public License v3.0 4 votes vote down vote up
@Override
public Observable<Theme> themeStream() {
    BehaviorSubject<Theme> stream = BehaviorSubject.create();
    return stream.startWith(new Theme(mSharedPreferences.getBoolean(mContext.getString(R.string.setting_verbose_enabled_key), false)));
}
 
Example 19
Source File: MyApp.java    From RxJavaExplained with Apache License 2.0 4 votes vote down vote up
@Override
public void onCreate() {
  super.onCreate();
  subject = BehaviorSubject.create();
}
 
Example 20
Source File: ChoiceOfTwoLoadBalancerTest.java    From ocelli with Apache License 2.0 3 votes vote down vote up
@Test(expected=NoSuchElementException.class)
public void testEmpty() {
    BehaviorSubject<List<Integer>> source = BehaviorSubject.create();
    
    LoadBalancer<Integer> lb = LoadBalancer.fromSnapshotSource(source).build(ChoiceOfTwoLoadBalancer.create(COMPARATOR));
    
    source.onNext(Lists.<Integer>newArrayList());
    
    lb.next();
}