Other Observable factory methods

Before moving forward with Observer, subscribing, unsubscribing, and Subjects, let's try our hands on a few other factory methods of Observable.

So, let's look at this code first, and then we will try to learn it line by line:

    fun main(args: Array<String>) { 
      val observer: Observer<Any> = object : Observer<Any> { 
        override fun onComplete() { 
            println("All Completed") 
        } 
 
        override fun onNext(item: Any) { 
            println("Next $item") 
        } 
 
        override fun onError(e: Throwable) { 
            println("Error Occured ${e.message}") 
        } 
 
        override fun onSubscribe(d: Disposable) { 
            println("New Subscription ") 
        } 
      }//Create Observer 
 
      Observable.range(1,10).subscribe(observer)//(1) 
      Observable.empty<String>().subscribe(observer)//(2) 
 
      runBlocking {    
Observable.interval(300,TimeUnit.MILLISECONDS).
subscribe(observer)//(3) delay(900) Observable.timer(400,TimeUnit.MILLISECONDS).
subscribe(observer)//(4) delay(450) } }

On comment (1), we created Observable with the Observable.range() factory method. This method creates an Observable and emits integers with the supplied start parameter until it emits a number of integers as per the count parameter.

On comment (2), we created Observable with the Observable.empty() method. This method creates Observable and emits onComplete() right away, without emitting any items with onNext().

On comment (3) and comment (4), we used two interesting Observable factory methods. The method on comment (3), Observable.interval(), emits numbers sequentially starting from 0, after each specified interval. It will continue emitting until you unsubscribe and until the program runs. Whereas, the method on comment (4), Observable.timer(), will emit only once with 0 after the specified time elapsed.

Here is the output if you are curious: