Java Code Examples for io.reactivex.disposables.Disposable#dispose()

The following examples show how to use io.reactivex.disposables.Disposable#dispose() . 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: BindingUtils.java    From android-mvvm with Apache License 2.0 6 votes vote down vote up
@BindingAdapter("adapter")
public static void bindAdapter(@NonNull ViewPager viewPager, @Nullable PagerAdapter adapter) {
    PagerAdapter oldAdapter = viewPager.getAdapter();

    // Disconnect previous adapter if its Connectable
    if (oldAdapter != null && oldAdapter instanceof Connectable) {
        Disposable subscription = (Disposable) viewPager.getTag(R.integer.tag_subscription);
        if (subscription != null && !subscription.isDisposed()) {
            subscription.dispose();
        }
        viewPager.setTag(R.integer.tag_subscription, null);
    }

    // Store connection (Subscription) if new adapter is Connectable
    if (adapter != null && adapter instanceof Connectable) {
        viewPager.setTag(R.integer.tag_subscription, ((Connectable) adapter).connect());
    }
    viewPager.setAdapter(adapter);
}
 
Example 2
Source File: UploadManager.java    From smart-farmer-android with Apache License 2.0 6 votes vote down vote up
/**
 * 取消多个上传任务
 */
public void removeTasks(Collection<T> tasks) {
    synchronized (monitor) {
        needRemoved.addAll(tasks);
        errorTask.removeAll(tasks);
        waitingTask.removeAll(tasks);
        for (T task : tasks) {
            UploadResponse<T, R> response = completedTask.get(task);
            if (response != null) {
                response.status = UploadStatus.STATUS_CANCEL;
            }

            Disposable disposable = taskDisposableMap.get(task);
            if (disposable != null) {
                disposable.dispose();
            }
        }
    }
}
 
Example 3
Source File: FlowableIT.java    From web3j with Apache License 2.0 6 votes vote down vote up
private <T> void run(Flowable<T> flowable) throws Exception {
    CountDownLatch countDownLatch = new CountDownLatch(EVENT_COUNT);
    CountDownLatch completedLatch = new CountDownLatch(EVENT_COUNT);

    Disposable subscription =
            flowable.subscribe(
                    x -> countDownLatch.countDown(),
                    Throwable::printStackTrace,
                    completedLatch::countDown);

    countDownLatch.await(TIMEOUT_MINUTES, TimeUnit.MINUTES);
    subscription.dispose();
    completedLatch.await(1, TimeUnit.SECONDS);

    log.info(
            "CountDownLatch={}, CompletedLatch={}",
            countDownLatch.getCount(),
            completedLatch.getCount());
    assertTrue(subscription.isDisposed());
}
 
Example 4
Source File: RxSQLiteTest.java    From SQLite with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testObserveTableChangeWithData() throws Exception {
    SQLite.get().enableAutomaticNotifications();

    Consumer<List<TestObject>> action = Mockito.mock(Consumer.class);
    Mockito.doNothing().when(action).accept(anyListOf(TestObject.class));
    Disposable disposable = RxSQLite.get().observeChanges(TestTable.TABLE).withQuery().subscribe(action);

    SQLite.get().insert(TestTable.TABLE, new TestObject(10410, 8.9, "ca'pcj;s;vhjvksf;bgd"));
    Thread.sleep(300);
    Mockito.verify(action).accept(anyListOf(TestObject.class));

    Mockito.reset(action);
    disposable.dispose();

    SQLite.get().delete(TestTable.TABLE);
    Thread.sleep(300);
    Mockito.verifyNoMoreInteractions(action);
}
 
Example 5
Source File: ClassicAsyncPerf.java    From akarnokd-misc with Apache License 2.0 6 votes vote down vote up
@Benchmark
public void flowableForkJoin(Blackhole bh) throws Exception {
    int c = count;
    CountDownLatch cdl = new CountDownLatch(1);

    Disposable d = flowableFJ.subscribe(j -> {
        if (j == c) {
            cdl.countDown();
        } else {
            bh.consume(j);
        }
    });

    for (int i = 1; i <= c; i++) {
        pp.onNext(i);
    }

    await(cdl, c);
    d.dispose();
}
 
Example 6
Source File: ReactivePVTest.java    From phoebus with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void demoPlain() throws Exception
{
    final PV pv = PVPool.getPV("sim://ramp(1, 1000, 0.1)");
     System.out.println("Subscribe to 10Hz value until we get 10 updates");
    final CountDownLatch count = new CountDownLatch(10);
    final Disposable dis = pv
        .onValueEvent(BackpressureStrategy.BUFFER)
        .subscribe(value ->
    {
        System.out.println(value);
        count.countDown();
    });
    count.await(10, TimeUnit.SECONDS);
    dis.dispose();

    PVPool.releasePV(pv);
}
 
Example 7
Source File: MainActivity.java    From Reactive-Android-Programming with MIT License 6 votes vote down vote up
private void demo1() {

        final Disposable subscribe = Observable.create(emitter -> {
            emitter.setCancellable(() -> {
                log("setCancellable");
                helloText.setOnClickListener(null);
            });
            helloText.setOnClickListener(v -> {
                log("listener", "Click");
                emitter.onNext(v);
            });
        })
                .doOnDispose(() -> log("onDispose"))
                .doOnComplete(() -> log("doOnComplete"))
                .subscribe(e -> log("subscribe", "Click"));
        subscribe.dispose();
    }
 
Example 8
Source File: Processor.java    From state-machine with Apache License 2.0 5 votes vote down vote up
private void cancel(Signal<?, Id> signal) {
    @SuppressWarnings("unchecked")
    CancelTimedSignal<Id> s = ((CancelTimedSignal<Id>) signal.event());
    @SuppressWarnings({ "unchecked", "rawtypes" })
    Disposable sub = subscriptions
            .remove(new ClassIdPair<Id>(new ClassId(s.fromClass(), s.fromId()),
                    new ClassId(signal.cls(), signal.id())));
    if (sub != null) {
        sub.dispose();
    }
}
 
Example 9
Source File: BasePresenter.java    From RxJava2RetrofitDemo with Apache License 2.0 5 votes vote down vote up
@Override
public void detachView() {
    for (Disposable disposable : disposables) {
        if (!disposable.isDisposed()) disposable.dispose();
    }
    mView = null;
}
 
Example 10
Source File: RxTimer.java    From Tangram-Android with MIT License 5 votes vote down vote up
public void unregister(OnTickListener onTickListener) {
    Disposable disposable = tickCache.get(onTickListener);
    if (disposable != null) {
        disposable.dispose();
        tickCache.remove(onTickListener);
    }
}
 
Example 11
Source File: SearchAdapter.java    From APlayer with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onViewRecycled(@NonNull SearchAdapter.SearchResHolder holder) {
  super.onViewRecycled(holder);
  if ((holder).mImage.getTag() != null) {
    Disposable disposable = (Disposable) (holder).mImage.getTag();
    if (!disposable.isDisposed()) {
      disposable.dispose();
    }
  }
  holder.mImage.setImageURI(Uri.EMPTY);
}
 
Example 12
Source File: ConcurrencyTest.java    From Java-programming-methodology-Rxjava-articles with Apache License 2.0 5 votes vote down vote up
@Test
void unsubscribeOn_test() {
    Disposable disposable =
            Observable.interval(1, TimeUnit.SECONDS)
                      .map(i -> "receive " +i)
                      .doOnDispose(()->	System.out.println("Disposing	on	thread	"
                              +	Thread.currentThread().getName()))
                      .unsubscribeOn(Schedulers.io())
                      .doOnDispose(()->	System.out.println("Disposing1	on	thread	"
                              +	Thread.currentThread().getName()))
                      .subscribe(ConcurrencyTest::log);
    sleep(4,TimeUnit.SECONDS);
    disposable.dispose();
    sleep(4,TimeUnit.SECONDS);
}
 
Example 13
Source File: LifeSingleObserver.java    From rxjava-RxLife with Apache License 2.0 5 votes vote down vote up
@Override
public void onSubscribe(Disposable d) {
    if (DisposableHelper.setOnce(this, d)) {
        try {
            addObserver();
            downstream.onSubscribe(d);
        } catch (Throwable ex) {
            Exceptions.throwIfFatal(ex);
            d.dispose();
            onError(ex);
        }
    }
}
 
Example 14
Source File: Rx2ApolloTest.java    From apollo-android with MIT License 5 votes vote down vote up
@Test
public void prefetchIsCanceledWhenDisposed() throws Exception {
  server.enqueue(Utils.INSTANCE.mockResponse(FILE_EPISODE_HERO_NAME_WITH_ID));

  TestObserver<EpisodeHeroNameQuery.Data> testObserver = new TestObserver<>();
  Disposable disposable = Rx2Apollo
      .from(apolloClient.prefetch(new EpisodeHeroNameQuery(Input.fromNullable(EMPIRE))))
      .observeOn(new TestScheduler())
      .subscribeWith(testObserver);

  disposable.dispose();

  testObserver.assertNotComplete();
  assertThat(testObserver.isDisposed()).isTrue();
}
 
Example 15
Source File: ReactivePVTest.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void demoBoggedThrottle() throws Exception
{
    final PV pv = PVPool.getPV("sim://ramp(1, 1000, 0.1)");

    System.out.println("Throttle a 10Hz value every 1 second, with a consumer that's stuck for 2 secs");
    System.out.println("Should see updates with values that are 20 apart every 2 seconds");

    final CountDownLatch count = new CountDownLatch(5);
    final Disposable dis = pv
        .onValueEvent(BackpressureStrategy.LATEST)
        .throttleLast(1, TimeUnit.SECONDS)
        .subscribe(value ->
        {
            count.countDown();
            System.out.println(value);
            System.out.println("-- busy for 2 sec --");
            try
            {
                TimeUnit.SECONDS.sleep(2);
            }
            catch (InterruptedException ex)
            {
                System.out.println("Interrupted");
            }
        });
    count.await();
    dis.dispose();

    PVPool.releasePV(pv);
}
 
Example 16
Source File: RxUtils.java    From MovieGuide with MIT License 4 votes vote down vote up
public static void unsubscribe(Disposable subscription) {
    if (subscription != null && !subscription.isDisposed()) {
        subscription.dispose();
    } // else subscription doesn't exist or already unsubscribed
}
 
Example 17
Source File: Rx.java    From klingar with Apache License 2.0 4 votes vote down vote up
public static void dispose(Disposable disposable) {
  if (disposable != null && !disposable.isDisposed()) {
    disposable.dispose();
  }
}
 
Example 18
Source File: StageDelays.java    From akarnokd-misc with Apache License 2.0 4 votes vote down vote up
@Test
    public void test2() throws Exception {
Scheduler ts = Schedulers.newThread();

long start = ts.now(TimeUnit.MILLISECONDS);

Map<Long, Long[]> state = new ConcurrentHashMap<>();

Disposable d = Flowable.interval(100, TimeUnit.MILLISECONDS, ts)
.onBackpressureLatest()
.doOnNext(v -> state.put(v, new Long[] { 0L, 0L, 0L, 0L }))
.delay(0, TimeUnit.MILLISECONDS, ts)
.doOnNext(v -> { 
    System.out.println("p50: " + v + " @ " + (ts.now(TimeUnit.MILLISECONDS) - start));
    state.get(v)[0] = ts.now(TimeUnit.MILLISECONDS) - start;
    Thread.sleep(50);
})
.delay(0, TimeUnit.MILLISECONDS, ts)
.doOnNext(v -> { 
    System.out.println("p500: " + v + " @ " + (ts.now(TimeUnit.MILLISECONDS) - start));
    state.get(v)[1] = ts.now(TimeUnit.MILLISECONDS) - start;
    Thread.sleep(500);
})
.delay(0, TimeUnit.MILLISECONDS, ts)
.doOnNext(v -> { 
    System.out.println("p200: " + v + " @ " + (ts.now(TimeUnit.MILLISECONDS) - start));
    state.get(v)[2] = ts.now(TimeUnit.MILLISECONDS) - start;
    Thread.sleep(200);
})
.rebatchRequests(1)
.subscribe(v -> {
    System.out.println("END: " + v + " @ " + (ts.now(TimeUnit.MILLISECONDS)  - start));
    state.get(v)[3] = ts.now(TimeUnit.MILLISECONDS) - start;
}, e -> { });

Thread.sleep(5000);

d.dispose();

Thread.sleep(200);

for (long v = 0; v < 100; v++) {
    if (state.containsKey(v)) {
        System.out.println(v);
        Long[] array = state.get(v);
        
        System.out.println("   p50: " + array[0]);
        System.out.println("  p500: " + array[1]);
        System.out.println("      : " + (array[1] - array[0]));
        System.out.println("  p200: " + array[2]);
        System.out.println("      : " + (array[2] - array[1]));
        System.out.println("   END: " + array[3]);
        System.out.println("      : " + (array[3] - array[2]));
    }
}
    }
 
Example 19
Source File: ChangesTest.java    From RxCupboard with Apache License 2.0 4 votes vote down vote up
@Test
public void changes_onSubscribed() {

	// Add observable to all database changes
	final AtomicInteger changeCount = new AtomicInteger();
	Disposable changes = rxDatabase.changes().subscribe(new Consumer<DatabaseChange>() {
		@Override
		public void accept(DatabaseChange databaseChange) throws Exception {
			changeCount.getAndIncrement();
		}
	});

	final TestEntity2 testEntity2 = new TestEntity2();
	testEntity2.date = new Date(System.currentTimeMillis());

	// Simple insert
	rxDatabase.putDirect(testEntity2);
	assertEquals(1, changeCount.get());

	// Simple update
	testEntity2.date = new Date(System.currentTimeMillis());
	rxDatabase.putDirect(testEntity2);
	assertEquals(2, changeCount.get());

	// Simple delete
	rxDatabase.deleteDirect(testEntity2);
	assertEquals(3, changeCount.get());

	// Unsubscribe from changes and repeat operations
	changes.dispose();

	final TestEntity2 pausedEntity2 = new TestEntity2();
	pausedEntity2.date = new Date(System.currentTimeMillis());

	// Simple insert
	rxDatabase.putDirect(pausedEntity2);
	assertEquals(3, changeCount.get());

	// Simple update
	pausedEntity2.date = new Date(System.currentTimeMillis());
	rxDatabase.putDirect(pausedEntity2);
	assertEquals(3, changeCount.get());

	// Simple delete
	rxDatabase.deleteDirect(pausedEntity2);
	assertEquals(3, changeCount.get());

}
 
Example 20
Source File: HotObservable.java    From rxjava2 with MIT License 3 votes vote down vote up
public static void main(String[] args) throws InterruptedException{

        ConnectableObservable<Long> numbers = (ConnectableObservable<Long>) Observable
                .interval(1, TimeUnit.SECONDS)     // generate numbers
                .publish();                        // make it hot

        numbers.connect();                        // create internal subscribtion
        
        Disposable subscriber1 = numbers
            .subscribe(n ->System.out.println("First subscriber: "+ n ));


        Thread.sleep(3000);

        Disposable subscriber2 = numbers
            .subscribe(n ->System.out.println("  Second subscriber: "+ n ));

        Thread.sleep(5000);
        System.out.println(">>> First subscriber goes for lunch break");
        subscriber1.dispose();

        Thread.sleep(5000);
        System.out.println("<<< First subscriber returned from lunch");
        subscriber1 = numbers.subscribe(n ->System.out.println("First subscriber: "+ n ));

        Thread.sleep(60000); // Just to keep the program running
    }