Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run standalone Completable on background thread

I am trying to create a completable and run it on background thread but it's not calling Action's run() when I am subscribing on Schedulers.io()

Basically I want to do following through RxAndroid:

     Thread t = new Thread(new Runnable() {
        public void run() {
            doSomething();
        }
    });
    t.start(); 

Using RxAndroid I am doing following:

   Completable.fromAction(new Action() {
        @Override
        public void run() throws Exception {
            doSomething();
        }
    }).subscribeOn(Schedulers.io());

It's run() method is not getting called if I do Schedulers.io(), but it gets called if I do subscribe().

I am unable to find why it's running when I subscribe for Schedulers.io().

like image 201
user1288005 Avatar asked Nov 20 '17 08:11

user1288005


1 Answers

Stream would executed only if it has been subscribed. It means, that your completable should be subscribed in order run() method to be executed. subscribeOn() does not subscribe to the stream, it just tells on which thread to subscribe.

In your example just adding subscribe() to the end would initiate run() method to be called:


    Completable.fromAction(new Action() {
        @Override
        public void run() throws Exception {
            doSomething();
        }
    })
    .subscribeOn(Schedulers.io())
    .subscribe(...);

like image 78
azizbekian Avatar answered Sep 30 '22 04:09

azizbekian