Fork us on GitHub

TIP: Streams are Observable in Codename One

You can get events from a stream to indicate progress
TIP: Streams are Observable in Codename One

TIP: Streams are Observable in Codename One

We got a pull request the other day that reminded me of some hidden functionality in Codename One that most developers aren’t aware of: observable input streams. By default Codename One API’s try to return BufferedInputStream and BufferedOutputStream instances from our internal API’s. Those classes aren’t the typical versions but rather ones from the package.

That API allows us to add functionality into the streams without breaking the Java compatibility or specs. One such feature is setProgressListener(IOProgressListener). This is probably better explained with a simple sample:

final Status status = ToastBar.getInstance().createStatus(); (1)
status.setMessage("Reading file");
BufferedInputStream bi; (2)
if(inputStream instanceof BufferedInputStream) {
   bi = (BufferedInputStream)inputStream;
} else {
   bi = new BufferedInputStream(inputStream);
bi.setProgressListener((source, bytes) -> { (3)
    callSerially(() -> status.setProgress(100 * bytes / streamLength)); (4)
1 The toastbar has a special mode that lets us display progress from 0 to 100
2 Since streams would often already be observable the `instanceof ` should be true for a few cases. In the exception this fallback would be reasonable
3 Notice that the progress listener carries an overhead and might slow your application. This might not be a big deal for some cases
4 The value is between 0 and 100 so we need to know the stream length in advance for the toastbar API


There are quite a few API’s in Codename One that are hidden under the surface. From our vantage point it’s often hard to remember everything that’s there even if we put it there. It’s worth asking us as some things can be hidden from view.

Share this Post:

Posted by Shai Almog

Shai is the co-founder of Codename One. He's been a professional programmer for over 25 years. During that time he has worked with dozens of companies including Sun Microsystems.
For more follow Shai on Twitter & github.