Created
October 13, 2016 23:19
-
-
Save murano500k/a43ca9debce1a0c6b476ff45594099d7 to your computer and use it in GitHub Desktop.
Rx background op
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package rx.android.samples; | |
import android.app.Activity; | |
import android.os.Bundle; | |
import android.os.HandlerThread; | |
import android.os.Looper; | |
import android.util.Log; | |
import android.view.View; | |
import java.util.concurrent.TimeUnit; | |
import rx.Observable; | |
import rx.Subscriber; | |
import rx.android.schedulers.AndroidSchedulers; | |
import rx.exceptions.OnErrorThrowable; | |
import rx.functions.Func0; | |
import static android.os.Process.THREAD_PRIORITY_BACKGROUND; | |
public class MainActivity extends Activity { | |
private static final String TAG = "RxAndroidSamples"; | |
private Looper backgroundLooper; | |
@Override protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.main_activity); | |
BackgroundThread backgroundThread = new BackgroundThread(); | |
backgroundThread.start(); | |
backgroundLooper = backgroundThread.getLooper(); | |
findViewById(R.id.button_run_scheduler).setOnClickListener(new View.OnClickListener() { | |
@Override public void onClick(View v) { | |
onRunSchedulerExampleButtonClicked(); | |
} | |
}); | |
} | |
void onRunSchedulerExampleButtonClicked() { | |
sampleObservable() | |
// Run on a background thread | |
.subscribeOn(AndroidSchedulers.from(backgroundLooper)) | |
// Be notified on the main thread | |
.observeOn(AndroidSchedulers.mainThread()) | |
.subscribe(new Subscriber<String>() { | |
@Override public void onCompleted() { | |
Log.d(TAG, "onCompleted()"); | |
} | |
@Override public void onError(Throwable e) { | |
Log.e(TAG, "onError()", e); | |
} | |
@Override public void onNext(String string) { | |
Log.d(TAG, "onNext(" + string + ")"); | |
} | |
}); | |
} | |
static Observable<String> sampleObservable() { | |
return Observable.defer(new Func0<Observable<String>>() { | |
@Override public Observable<String> call() { | |
try { | |
// Do some long running operation | |
Thread.sleep(TimeUnit.SECONDS.toMillis(5)); | |
} catch (InterruptedException e) { | |
throw OnErrorThrowable.from(e); | |
} | |
return Observable.just("one", "two", "three", "four", "five"); | |
} | |
}); | |
} | |
static class BackgroundThread extends HandlerThread { | |
BackgroundThread() { | |
super("SchedulerSample-BackgroundThread", THREAD_PRIORITY_BACKGROUND); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment