How do I run `Observable` in a separate thread?

I use RxJava in Scala project and say I have this simple Observable:

Observable[String](observer => while (true) observer onNext "hi")
  .subscribe(v => println(v))

println("hello")

I will never get to "hello" message because while blocks a thread. How can I run my Observable in a separate thread to avoid blocking?

==================================

I was thinking observeOn could help but it does not. Running this:

val s = rx.lang.scala.schedulers.NewThreadScheduler.apply

Observable[String](observer => while (true) observer onNext "hi")
  .observeOn(s).subscribe(v => println(v))

println("hello")

...still does not print "hello". I guess adding observeOn makes OnNext to be called in a separate thread but not a while block itself?

==================================

I could of course wrap while in a Future:

Observable[String](observer => Future { while (true) observer onNext "hi" })
  .subscribe(v => println(v))

println("test") // "test" gets printed

But perhaps there are more rx-idiomatic ways of doing this exist?

Answers


You need to use subscribeOn. E.g.,

Observable[String](observer => while (true) observer onNext "hi").subscribeOn(s)
  .subscribe(v => println(v))

subscribeOn will call the subscribe function in the Scheduler, while observeOn will dispatch the messages to the Scheduler.


Need Your Help

How to not use application.html.erb file for a particular page in application?

ruby-on-rails ruby-on-rails-3 web-applications partial-views

I want a particular page in the application to have different layout, while all others will have pretty much the same layout. However, the application.html.erb file is rendered for all the pages in

Call parent function passed as prop in React

javascript twitter-bootstrap reactjs jsx

I'm creating a survey-type app in React. The questions are arranged as items in a carousel.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.