a_dzik
a_dzik

Reputation: 977

Using RxJava to handle costly operations

I'm quite new to RxJava so I'm still having a hard time using it. I read lots of blog posts and such, and I'm still a bit lost.

So - I want to get a list of all installed apps. Simple enough. Instead of running it inside of an asynchtask I'm trying to be a bit more fancy and use RxJava.

My idea was to do something like this:

    private void test(){
    Observable.from(getInstalledApps(true))
                .observeOn(Schedulers.newThread())
                .map(s -> s.appname)
                .subscribe(s -> L.d(TAG, "app: " + s));

}

But then I realized this won't work, because "observeOn" applies only to .map, not to method itself.

After that I tried to feed Observable with some empty value, and launch method inside .map - no luck.

What is the proper way to do it?

Upvotes: 1

Views: 106

Answers (1)

dwursteisen
dwursteisen

Reputation: 11515

Recarding your code, it can be rewrited like this :

 List apps = getInstalledApps(true)
 Observable.from()
            .observeOn(Schedulers.newThread())
            .map(s -> s.appname)
            .subscribe(s -> L.d(TAG, "app: " + s)); 

As you can see, getInstalledApp will be called in the current thread. You'll have to "defert" this call. To do this, you can build your own Observable :

 Observable<List> myObs = Observable.create(subscriber -> {
         List result = getInstalledApp(true);
         subscriber.onNext(result);
         subscriber.onCompleted();
  }); 

then you can interract with your Observable :

 myObs.subscribeOn(Schedulers.newThread()).subscribe();

like this, your Observable will call your subscription code into a new thread.

Upvotes: 2

Related Questions