I want to create an Observable that will emit items on demand, that means I want a single subscribe to Observable and notify Observable that I need new item based on my request.
This is what I have done using PublishSubject:
public class RecognizeSubject {
PublishSubject<Bitmap> mSubject;
private Context mContext;
private FaceDetector mFaceDetecor;
public RecognizeSubject(Context mContext) {
this.mContext = mContext;
this.mSubject = PublishSubject.create();
}
public void detect(Bitmap btm){
mSubject.onNext(btm);
}
public Flowable<SinglePhotoId> execute() {
return mSubject.toFlowable(BackpressureStrategy.DROP)
.observeOn(Schedulers.newThread())
.map(bitmap1 -> recognize(bitmap1))
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe(disposable -> initialize())
.doFinally(() -> release());
}
private void initialize() {
mFaceDetecor = new FaceDetector.Builder(mContext)
.setTrackingEnabled(false)
.setLandmarkType(FaceDetector.ALL_LANDMARKS)
.build();
}
private void release() {
if (mFaceDetecor != null)
mFaceDetecor.release();
}
private SinglePhotoId recognize(Bitmap bitmap) {
//SystemClock.sleep(3000);
//make hard background work and return SinglePhotoId object
}
}
and here is a usage in Activity class:
private void takeSubjectSnap() {
if (mSubject == null)
mSubject = new RecognizeSubject(getBaseContext());
if (mDisposable == null || mDisposable.isDisposed()) {
mDisposable = mSubject.execute()
.subscribe(this::handleDetectionSuccess,
this::handleDetectionError,
this::handleDetectionCompleted);
}
mSnapshotButton.setProgress(true);
mSubject.detect(myVideoView.getBitmap());
}
So basically I subscribe to Flowable object and pass Bitmap object to my Subject class to proceed and return result via Flowable, is that solution right or can produce some memory leaks?
Is there any better solution to send an object to Observable to proceed and return result via a standard onNext() method?