android - How do I access the main thread after a background thread completes in RxJava? -


i have observable io processing on background thread:

progressbar.setvisibility(view.visible); observable.create(new onsubscribe<file>() {          @override public void call(subscriber<? super file> subscriber) {             inputstream inputstream = null;             fileoutputstream outputstream = null;              try {                 if (environment.getexternalstoragestate().equals(environment.media_mounted)){                     url url = new url(downloadurl);                     urlconnection conn = url.openconnection();                     inputstream = conn.getinputstream();                      file savedir = environment.getexternalstoragepublicdirectory(environment.directory_downloads);                     file downloadedfile = new file(savedir, filename);                     outputstream = new fileoutputstream(downloadedfile);                     byte[] buffer = new byte[4096];                     int bytesread = -1;                     while ((bytesread = inputstream.read(buffer)) != -1) {                         outputstream.write(buffer, 0, bytesread);                     }                 }             } 

after io work done, want hide progressbar. of course cannot inside call(subscriber) of anonymous class because accessing ui elements io thread throw exception.

i believe common pattern .observeon(androidschedulers.mainthread()). using lambdas brevity:

progressbar.setvisibility(view.visible); observable.create(new onsubscribe<file()...)   .subscribeon(schedulers.io())   .observeon(androidschedulers.mainthread())   .dooncompleted(() -> progressbar.setvisibility(invisible))   .subscribe(file -> {}, error -> reporterror(error)); 

if want hide progress bar on completion or error replace .dooncompleted .doonterminate.

a quick warning should damndest avoid observable.create because of backpressure starters.


Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -