DumDumGenius
DumDumGenius

Reputation: 173

How To Use Threading on RxJava?

        Observable.create(new Observable.OnSubscribe<Integer>() {

        public void call(final Subscriber<? super Integer> obs) {
            new Thread(){
                public void run(){
                    obs.onNext(1);
                }
            }.start();
            new Thread(){
                public void run(){
                    obs.onNext(2);
                }
            }.start();
            new Thread(){
                public void run(){
                    obs.onNext(3);
                }
            }.start();
            obs.onCompleted();
        }
    }).subscribe(new Subscriber<Integer>(){

        public void onCompleted() {
            System.out.println("Complete");

        }

        public void onError(Throwable arg0) {
            // TODO Auto-generated method stub

        }

        public void onNext(Integer arg0) {
            System.out.println(arg0);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    });

As you see , I want to do multi-threading on Java with RxJava

I've studied many resources on Google , but most of them are for Android

Can anybody tell what is the easiest way to implement it ?

I think my code is a little :<

Upvotes: 1

Views: 161

Answers (1)

Tassos Bassoukos
Tassos Bassoukos

Reputation: 16142

Well, it's a bit unclear what you're asking, but it is worthwhile to at least have a cursory read over the Observable class, as it has a lot of methods that will make your life easier. For example, your code roughly translates to:

 Observable
 .just(1,2,3)
 .subscribeOn(Schedulers.io())
 .zipWith(Observable.interval(1000,1000,TimeUnit.milliseconds),
     (item, pos) -> item)
 .doOnCompleted(() -> System.out.println("Complete");
 .subscribe(item -> System.out.println(item));

However, you first need to be clear on what do you want to do - can you put it to words?

Upvotes: 3

Related Questions