The Mono publisher

The Mono publisher works in a similar way to Flux, but can only emit no values or a single value. We can use this to perform a request to a server and return the result.

The following example code makes a request and receives an instance of the Comic class, loading an instance of the Bitmap class and displaying the retrieved image:

Mono.fromDirect<Comic> { subscriber -> subscriber.onNext(loadComic()) }
.map { comic -> comic.img }
.flatMap { path -> Mono.fromDirect<Bitmap> { subscriber -> subscriber.onNext(loadBitmap(path)) } }
.subscribeOn(Schedulers.single())
.subscribe { bitmap ->
Handler(Looper.getMainLooper()).post {
findViewById<ImageView>(R.id.imageView).setImageBitmap(bitmap)
}
}

The subscribeOn method is used to specify a scheduler for long-term tasks. Let's run this example, as follows:

The preceding snippet retrieves an instance of the Comic class, transforms it to a path to an image, loads the image, and then shows a downloaded image.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.136.17.12