Java Code Examples for android.support.annotation.MainThread

The following are top voted examples for showing how to use android.support.annotation.MainThread. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: xlight_android_native   File: ParticleDevice.java   View source code 6 votes vote down vote up
/**
 * Subscribes to system events of current device. Events emitted to EventBus listener.
 *
 * @throws ParticleCloudException Failure to subscribe to system events.
 * @see <a href="https://github.com/greenrobot/EventBus">EventBus</a>
 */
@MainThread
public void subscribeToSystemEvents() throws ParticleCloudException {
    try {
        EventBus eventBus = EventBus.getDefault();
        subscriptions.add(subscribeToSystemEvent("spark/status", (eventName, particleEvent) ->
                sendUpdateStatusChange(eventBus, particleEvent.dataPayload)));
        subscriptions.add(subscribeToSystemEvent("spark/flash/status", (eventName, particleEvent) ->
                sendUpdateFlashChange(eventBus, particleEvent.dataPayload)));
        subscriptions.add(subscribeToSystemEvent("spark/device/app-hash", (eventName, particleEvent) ->
                sendSystemEventBroadcast(new DeviceStateChange(ParticleDevice.this,
                        ParticleDeviceState.APP_HASH_UPDATED), eventBus)));
        subscriptions.add(subscribeToSystemEvent("spark/status/safe-mode", (eventName, particleEvent) ->
                sendSystemEventBroadcast(new DeviceStateChange(ParticleDevice.this,
                        ParticleDeviceState.SAFE_MODE_UPDATER), eventBus)));
        subscriptions.add(subscribeToSystemEvent("spark/safe-mode-updater/updating", (eventName, particleEvent) ->
                sendSystemEventBroadcast(new DeviceStateChange(ParticleDevice.this,
                        ParticleDeviceState.ENTERED_SAFE_MODE), eventBus)));
    } catch (IOException e) {
        log.d("Failed to auto-subscribe to system events");
        throw new ParticleCloudException(e);
    }
}
 
Example 2
Project: RIBs   File: Router.java   View source code 6 votes vote down vote up
/**
 * Detaches the {@param childFactory} from the current {@link Interactor}. NOTE: No consumers of
 * this API should ever keep a reference to the detached child router, leak canary will enforce
 * that it gets garbage collected.
 *
 * <p>If you need to keep references to previous routers, use {@link RouterNavigator}.
 *
 * @param childRouter the {@link Router} to be detached.
 */
@MainThread
protected void detachChild(Router childRouter) {
  children.remove(childRouter);

  Interactor interactor = childRouter.getInteractor();
  ribRefWatcher.watchDeletedObject(interactor);
  ribRefWatcher.logBreadcrumb(
      "DETACHED", childRouter.getClass().getSimpleName(), this.getClass().getSimpleName());
  if (savedInstanceState != null) {
    Bundle childrenBundles =
        checkNotNull(savedInstanceState.getBundleExtra(KEY_CHILD_ROUTERS));
    childrenBundles.putBundleExtra(childRouter.tag, null);
  }

  childRouter.dispatchDetach();
}
 
Example 3
Project: HtmlNative   File: HNViewTypeManager.java   View source code 6 votes vote down vote up
@MainThread
static synchronized void registerViewType(HNViewType viewType) {
    if (viewType.getViewClass() != null && viewType.getHTMLType() != null) {
        ViewTypeRelations.registerExtraView(viewType.getViewClass().getName(), viewType
                .getHTMLType());

        StyleHandlerFactory.registerExtraStyleHandler(viewType.getViewClass(), viewType);
        HNRenderer.registerViewFactory(viewType.getViewClass().getName(), viewType);

        Set<String> inheritStyleNames = viewType.onInheritStyleNames();
        if (inheritStyleNames != null && !inheritStyleNames.isEmpty()) {
            for (String style : inheritStyleNames) {
                if (!InheritStylesRegistry.isPreserved(style)) {
                    InheritStylesRegistry.register(style);
                }
            }
        }
    }
}
 
Example 4
Project: NewAndroidArchitecture   File: CountriesViewModel.java   View source code 6 votes vote down vote up
@MainThread
@NonNull
LiveData<Response<List<Country>>> getMoviesList() {
    if (countriesLiveData == null) {
        countriesLiveData = new MutableLiveData<>();
        countriesRepository.getCountries()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(disposable -> loadingLiveData.setValue(true))
                .doAfterTerminate(() -> loadingLiveData.setValue(false))
                .subscribe(
                        countries1 -> countriesLiveData.setValue(Response.success(countries1)),
                        throwable -> countriesLiveData.setValue(Response.error(throwable))
                );
    }
    return countriesLiveData;
}
 
Example 5
Project: code-scanner   File: CodeScanner.java   View source code 6 votes vote down vote up
/**
 * Camera to use
 *
 * @param cameraId Camera id (between {@code 0} and
 *                 {@link Camera#getNumberOfCameras()} - {@code 1})
 */
@MainThread
public void setCamera(int cameraId) {
    mInitializeLock.lock();
    try {
        if (mCameraId != cameraId) {
            mCameraId = cameraId;
            if (mInitialized) {
                boolean previewActive = mPreviewActive;
                releaseResources();
                if (previewActive) {
                    initialize();
                }
            }
        }
    } finally {
        mInitializeLock.unlock();
    }
}
 
Example 6
Project: vlc-example-streamplayer   File: AWindow.java   View source code 6 votes vote down vote up
@MainThread
private void onSurfaceCreated() {
    if (mSurfacesState.get() != SURFACE_STATE_ATTACHED)
        throw new IllegalArgumentException("invalid state");

    final SurfaceHelper videoHelper = mSurfaceHelpers[ID_VIDEO];
    final SurfaceHelper subtitlesHelper = mSurfaceHelpers[ID_SUBTITLES];
    if (videoHelper == null)
        throw new NullPointerException("videoHelper shouldn't be null here");

    if (videoHelper.isReady() && (subtitlesHelper == null || subtitlesHelper.isReady())) {
        mSurfacesState.set(SURFACE_STATE_READY);
        for (IVLCVout.Callback cb : mIVLCVoutCallbacks)
            cb.onSurfacesCreated(this);
        if (mSurfaceCallback != null)
            mSurfaceCallback.onSurfacesCreated(this);
    }
}
 
Example 7
Project: RIBs   File: Router.java   View source code 6 votes vote down vote up
/**
 * Attaches a child router to this router.
 *
 * @param childRouter the {@link Router} to be attached.
 * @param tag an identifier to namespace saved instance state {@link Bundle} objects.
 */
@MainThread
protected void attachChild(Router<?, ?> childRouter, String tag) {
  for (Router child : children) {
    if (tag.equals(child.tag)) {
      Rib.getConfiguration()
          .handleNonFatalWarning(
              String.format(
                  Locale.getDefault(), "There is already a child router with tag: %s", tag),
              null);
    }
  }

  children.add(childRouter);
  ribRefWatcher.logBreadcrumb(
      "ATTACHED", childRouter.getClass().getSimpleName(), this.getClass().getSimpleName());
  Bundle childBundle = null;
  if (this.savedInstanceState != null) {
    Bundle previousChildren =
        checkNotNull(this.savedInstanceState.getBundleExtra(KEY_CHILD_ROUTERS));
    childBundle = previousChildren.getBundleExtra(tag);
  }

  childRouter.dispatchAttach(childBundle, tag);
}
 
Example 8
Project: Fairy   File: MergeResource.java   View source code 6 votes vote down vote up
@MainThread
public void initData() {
    executors.getDiskIO().execute(() -> {
        LiveData<LocalType> dbSource = loadFromDb();
        executors.getMainExecutor().execute(() -> {
            result.addSource(dbSource, dbData -> {
                result.removeSource(dbSource);
                if (dbData != null) {
                    ZLog.d("db------" + dbData.toString());
                    setValue(dbData);
                    appendResult(castLocalToNet(dbData));
                }
            });
        });
    });
}
 
Example 9
Project: Fairy   File: GrepFilter.java   View source code 6 votes vote down vote up
@MainThread
static LiveData<LogcatContent> grepData(LiveData<LogcatContent> rawData, String grep) {
    return Transformations.map(rawData, logcatData -> {
        String content = logcatData.getContent();
        if (GREP_SIGNAL.equals(content)) {
            return logcatData;
        }


        if (content != null) {
            logcatData.setContent(parseHtml2(content,grep));
        }

        return logcatData;

    });
}
 
Example 10
Project: vlc-example-streamplayer   File: Dialog.java   View source code 5 votes vote down vote up
/**
 * Post an answer
 *
 * @param username valid username (can't be empty)
 * @param password valid password (can be empty)
 * @param store if true, store the credentials
 */
@MainThread
public void postLogin(String username, String password, boolean store) {
    if (mId != 0) {
        nativePostLogin(mId, username, password, store);
        mId = 0;
    }
}
 
Example 11
Project: MiniDownloader   File: MiniDownloader.java   View source code 5 votes vote down vote up
/**
 * Check task whether valid.
 *
 * @param task
 * @return
 */
@MainThread
private void checkTask(@NonNull Task task) {
    if (task == null
            || task.getUrlStr() == null
            || task.getFilePath() == null
            || task.getListener() == null
            || task.getErrorListener() == null) {
        throw new IllegalArgumentException("task ,urlStr, filePath, listener, errorListener must not be null!");
    }
}
 
Example 12
Project: GitHub   File: PresenterManager.java   View source code 5 votes vote down vote up
/**
 * Get the  {@link ActivityScopedCache} for the given Activity or <code>null</code> if no {@link
 * ActivityScopedCache} exists for the given Activity
 *
 * @param activity The activity
 * @return The {@link ActivityScopedCache} or null
 * @see #getOrCreateActivityScopedCache(Activity)
 */
@Nullable @MainThread static ActivityScopedCache getActivityScope(@NonNull Activity activity) {
  if (activity == null) {
    throw new NullPointerException("Activity is null");
  }
  String activityId = activityIdMap.get(activity);
  if (activityId == null) {
    return null;
  }

  return activityScopedCacheMap.get(activityId);
}
 
Example 13
Project: SampleAppArch   File: NetworkBoundResource.java   View source code 5 votes vote down vote up
@MainThread
public NetworkBoundResource(AppExecutors appExecutors) {
  this.appExecutors = appExecutors;
  result.setValue(Resource.loading(null));
  LiveData<ResultType> dbSource = loadFromDb();
  result.addSource(dbSource, data -> {
    result.removeSource(dbSource);
    if (shouldFetch(data)) {
      fetchFromNetwork(dbSource);
    } else {
      result.addSource(dbSource, newData -> setValue(Resource.success(newData)));
    }
  });
}
 
Example 14
Project: Android-Code-Demos   File: SingleLiveEvent.java   View source code 5 votes vote down vote up
@MainThread
public void observe(LifecycleOwner owner, final Observer<T> observer) {
    if (hasActiveObservers()) {
        Log.w(TAG, "Multiple observers registered but only one will be notified of changes.");
    }

    super.observe(owner, new Observer<T>() {
        @Override
        public void onChanged(@Nullable T t) {
            if (mPending.compareAndSet(true, false)) {
                observer.onChanged(t);
            }
        }
    });
}
 
Example 15
Project: FitnessHabits   File: FitnessHabitsApplication.java   View source code 5 votes vote down vote up
@MainThread
public ParamRepository getParamRepository() {
    if (paramRepository == null) {
        paramRepository = new ParamRepository(getDatabase().paramRecordDao());
    }
    return paramRepository;
}
 
Example 16
Project: FitnessHabits   File: FoodDataRepository.java   View source code 5 votes vote down vote up
@SuppressLint("StaticFieldLeak")
@MainThread
public void saveFoodEntry(FoodEntry entry) {
    new AsyncTask<Void,Void,Void>() {
        @Override
        protected Void doInBackground(Void... voids) {
            foodDataDao.insertOrReplaceFoodEntry(entry);
            return null;
        }
    }.execute();
}
 
Example 17
Project: LoadMoreHelper   File: LoadController.java   View source code 5 votes vote down vote up
/**
 * Call when 1st page data loaded
 */
@MainThread
private void onPullDataEnd() {
    isPullingData = false;
    if (isDestoryed) {
        return;
    }
    if (paramBuilder.pullView != null) {
        paramBuilder.pullView.doPullEnd();
    }
}
 
Example 18
Project: FitnessHabits   File: DrinkRepository.java   View source code 5 votes vote down vote up
/**
 * Add value to a id for a certain date
 */
@SuppressLint("StaticFieldLeak")
@MainThread
public void replaceAmountCurrentDay(int categoryId, int amount) {
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... voids) {
            drinkDataDAO.replaceDrink(categoryId,amount);
            return null;
        }
    }.execute();
}
 
Example 19
Project: FitnessHabits   File: CommentDataRepository.java   View source code 5 votes vote down vote up
@SuppressLint("StaticFieldLeak")
@MainThread
public void saveAlcoolComment(CommentData comment) {
    new AsyncTask<Void,Void,Void>() {
        @Override
        protected Void doInBackground(Void... voids) {
            comment.setCategory(0);
            commentDataDao.insertOrUpdateComment(comment);
            return null;
        }
    }.execute();
}
 
Example 20
Project: vlc-example-streamplayer   File: MediaBrowser.java   View source code 5 votes vote down vote up
/**
 * Browse to the specified local path starting with '/'.
 *
 * @param path
 * @param flags see {@link Flag}
 */
@MainThread
public void browse(String path, int flags) {
    final Media media = new Media(mLibVlc, path);
    browse(media, flags);
    media.release();
}
 
Example 21
Project: ViewPump   File: ViewPump.java   View source code 5 votes vote down vote up
@MainThread
public static ViewPump get() {
    if (INSTANCE == null) {
        INSTANCE = builder().build();
    }
    return INSTANCE;
}
 
Example 22
Project: tumbviewer   File: TransferAction.java   View source code 5 votes vote down vote up
@MainThread
void transferFinish() {
    if (progressRef != null) {
        DownloadService.DownloadProgress progress = progressRef.get();
        if (progress != null) {
            progress.onDownloadFinish();
        }
    }
}
 
Example 23
Project: FitnessHabits   File: AlcoolRepository.java   View source code 5 votes vote down vote up
@SuppressLint("StaticFieldLeak")
@MainThread
public void saveAlcoolDrinkEntry(DrinkEntry entry) {
    new AsyncTask<Void,Void,Void>() {
        @Override
        protected Void doInBackground(Void... voids) {
            drinkDataDAO.insetOrReplaceDrinkEntry(entry);
            return null;
        }
    }.execute();
}
 
Example 24
Project: FitnessHabits   File: AlcoolRepository.java   View source code 5 votes vote down vote up
/**
 * Create a new alcool category
 * @param category (category.type is not required, it will be set anyways)
 */
@SuppressLint("StaticFieldLeak")
@MainThread
public void saveAlcoolDrinkCategory(DrinkCategory category) {
    new AsyncTask<Void,Void,Void>() {
        @Override
        protected Void doInBackground(Void... voids) {
            category.setType(0);
            drinkDataDAO.insetOrReplaceDrinkCategory(category);
            return null;
        }
    }.execute();
}
 
Example 25
Project: Watermark   File: PresenterManager.java   View source code 5 votes vote down vote up
/**
 * Get the  {@link ActivityScopedCache} for the given Activity or <code>null</code> if no {@link
 * ActivityScopedCache} exists for the given Activity
 *
 * @param activity The activity
 * @return The {@link ActivityScopedCache} or null
 * @see #getOrCreateActivityScopedCache(Activity)
 */
@Nullable @MainThread static ActivityScopedCache getActivityScope(@NonNull Activity activity) {
  if (activity == null) {
    throw new NullPointerException("Activity is null");
  }
  String activityId = activityIdMap.get(activity);
  if (activityId == null) {
    return null;
  }

  return activityScopedCacheMap.get(activityId);
}
 
Example 26
Project: FitnessHabits   File: SleepRepository.java   View source code 5 votes vote down vote up
@SuppressLint("StaticFieldLeak")
@MainThread
public void saveSleepEntry(SleepEntry entry) {
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... voids) {
            sleepEntryDAO.insertNewEntry(entry);
            return null;
        }
    }.execute();
}
 
Example 27
Project: FitnessHabits   File: ParamManager.java   View source code 5 votes vote down vote up
@SuppressLint("StaticFieldLeak")
@MainThread
public void saveParamRecord(ParamRecord record) {

    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... voids) {
            paramRecordDao.saveParamRecord(record);
            return null;
        }
    }.execute();


}
 
Example 28
Project: NSMPlayer-Android   File: ConnectionUtils.java   View source code 5 votes vote down vote up
/**
 * 仅当监听到网络连接成功后触发一次,只触发唯一一次
 * @param listener 触发监听器
 */
@MainThread
public static void triggerOnceUponConnected(final OnConnectedListener listener) {
    register(new OnConnectionChangeListener() {
        @Override
        public void onConnectionChange(Intent connectivityIntent) {
            if (isNetworkConnected()) {
                unregister(this);
                listener.onConnected();
            }
        }
    });
}
 
Example 29
Project: realm-helpers   File: RealmComputableLiveData.java   View source code 5 votes vote down vote up
@MainThread
@Override
public void run() {
    boolean isActive = mLiveData.hasActiveObservers();
    if (mInvalid.compareAndSet(false, true)) {
        if (isActive) {
            realmQueryExecutor.execute(mRefreshRunnable);
        }
    }
}
 
Example 30
Project: vlc-example-streamplayer   File: MediaBrowser.java   View source code 5 votes vote down vote up
/**
 * Browse to the specified uri.
 *
 * @param uri
 * @param flags see {@link Flag}
 */
@MainThread
public void browse(Uri uri, int flags) {
    final Media media = new Media(mLibVlc, uri);
    browse(media, flags);
    media.release();
}
 
Example 31
Project: vlc-example-streamplayer   File: MediaBrowser.java   View source code 5 votes vote down vote up
/**
 * Release the MediaBrowser.
 */
@MainThread
public void release() {
    reset();
    if (!mAlive)
        throw new IllegalStateException("MediaBrowser released more than one time");
    mLibVlc.release();
    mAlive = false;
}
 
Example 32
Project: code-scanner   File: CodeScanner.java   View source code 5 votes vote down vote up
/**
 * Formats, decoder to react to ({@link #ALL_FORMATS} by default)
 *
 * @param formats Formats
 * @see BarcodeFormat
 * @see #ALL_FORMATS
 * @see #ONE_DIMENSIONAL_FORMATS
 * @see #TWO_DIMENSIONAL_FORMATS
 */
@MainThread
public void setFormats(@NonNull List<BarcodeFormat> formats) {
    mInitializeLock.lock();
    try {
        mFormats = formats;
        if (mInitialized) {
            mDecoderWrapper.getDecoder().setFormats(formats);
        }
    } finally {
        mInitializeLock.unlock();
    }
}
 
Example 33
Project: code-scanner   File: CodeScanner.java   View source code 5 votes vote down vote up
/**
 * Auto focus mode, {@link AutoFocusMode#SAFE} by default
 *
 * @see AutoFocusMode
 */
@MainThread
public void setAutoFocusMode(@NonNull AutoFocusMode autoFocusMode) {
    mInitializeLock.lock();
    try {
        mAutoFocusMode = autoFocusMode;
        if (mInitialized && mAutoFocusEnabled) {
            setAutoFocusEnabledInternal(true);
        }
    } finally {
        mInitializeLock.unlock();
    }
}
 
Example 34
Project: code-scanner   File: CodeScanner.java   View source code 5 votes vote down vote up
/**
 * Whether to enable or disable flash light if it's supported, {@code false} by default
 */
@MainThread
public void setFlashEnabled(boolean flashEnabled) {
    mInitializeLock.lock();
    try {
        boolean changed = mFlashEnabled != flashEnabled;
        mFlashEnabled = flashEnabled;
        mScannerView.setFlashEnabled(flashEnabled);
        if (mInitialized && mPreviewActive && changed && mDecoderWrapper.isFlashSupported()) {
            setFlashEnabledInternal(flashEnabled);
        }
    } finally {
        mInitializeLock.unlock();
    }
}
 
Example 35
Project: EpubReaderAndroid   File: WebViewHelper.java   View source code 5 votes vote down vote up
@MainThread
private void executeCommand(String javascriptCommand) {
    javascriptCommand = "javascript:" + javascriptCommand;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        webView.evaluateJavascript(javascriptCommand, null);
    } else {
        webView.loadUrl(javascriptCommand);
    }
}
 
Example 36
Project: code-scanner   File: CodeScanner.java   View source code 5 votes vote down vote up
/**
 * Release resources, and stop preview if needed; call this method in {@link Activity#onPause()}
 */
@MainThread
public void releaseResources() {
    if (mInitialized) {
        if (mPreviewActive) {
            stopPreview();
        }
        releaseResourcesInternal();
    }
}
 
Example 37
Project: Saiy-PS   File: ClipboardHelper.java   View source code 5 votes vote down vote up
/**
 * Static method to get the primary clipboard content, or the relevant error string.
 *
 * @param ctx the application context
 * @return the clipboard content or error text
 */
@MainThread
public static Pair<Boolean, String> getClipboardContentPair(@NonNull final Context ctx, @NonNull final SupportedLanguage sl) {

    final String content = getClipboardContent();

    if (UtilsString.notNaked(content)) {
        return new Pair<>(true, content);
    } else {
        return new Pair<>(false, PersonalityResponse.getClipboardDataError(ctx, sl));
    }
}
 
Example 38
Project: vlc-example-streamplayer   File: Dumper.java   View source code 5 votes vote down vote up
/**
 * Create a Dumper that will download an Uri into a local filesystem path
 * @param uri the Uri to dump
 * @param filepath local filesystem path where to dump the Uri
 * @param listener listener in order to be notified when the dump is finished
 */
@MainThread
public Dumper(Uri uri, String filepath, Listener listener) {
    if (uri == null || filepath == null || listener == null)
        throw new IllegalArgumentException("arguments shouldn't be null");
    mListener = listener;

    ArrayList<String> options = new ArrayList<>(8);
    options.add("--demux");
    options.add("dump2,none");
    options.add("--demuxdump-file");
    options.add(filepath);
    options.add("--no-video");
    options.add("--no-audio");
    options.add("--no-spu");
    options.add("-vv");
    mLibVLC = new LibVLC(null, options);

    final Media media = new Media(mLibVLC, uri);
    mMediaPlayer = new MediaPlayer(media);
    mMediaPlayer.setEventListener(new MediaPlayer.EventListener() {
        @Override
        public void onEvent(MediaPlayer.Event event) {
            switch (event.type) {
                case MediaPlayer.Event.Buffering:
                    mListener.onProgress(event.getBuffering());
                    break;
                case MediaPlayer.Event.EncounteredError:
                case MediaPlayer.Event.EndReached:
                    mListener.onFinish(event.type == MediaPlayer.Event.EndReached);
                    cancel();
                    break;
            }

        }
    });
    media.release();
}
 
Example 39
Project: code-scanner   File: CodeScanner.java   View source code 5 votes vote down vote up
/**
 * Set auto focus mode, {@link AutoFocusMode#SAFE} by default
 *
 * @see AutoFocusMode
 */
@NonNull
@MainThread
public Builder autoFocusMode(@NonNull AutoFocusMode mode) {
    mAutoFocusMode = mode;
    return this;
}
 
Example 40
Project: RxCommand   File: RxCommand.java   View source code 5 votes vote down vote up
/**
 * If the receiver is enabled, this method will:
 * <p>
 * 1. Invoke the `func` given at the time of creation.
 * 2. Multicast the returned observable.
 * 3. Send the multicasted observable on {@link #executionObservables()}.
 * 4. Subscribe (connect) to the original observable on the main thread.
 *
 * @param input The input value to pass to the receiver's `func`. This may be null.
 * @return the multicasted observable, after subscription. If the receiver is not
 * enabled, returns a observable that will send an error.
 */
@MainThread
public final Observable<T> execute(@Nullable Object input) {
    boolean enabled = mImmediateEnabled.blockingFirst();
    if (!enabled) {
        return Observable.error(new IllegalStateException("The command is disabled and cannot be executed"));
    }
    try {
        Observable<T> observable = mFunc.apply(input);
        if (observable == null) {
            throw new RuntimeException(String.format("null Observable returned from observable func for value %s", input));
        }

        // This means that `executing` and `enabled` will send updated values before
        // the observable actually starts performing work.
        final ConnectableObservable<T> connection = observable
                .subscribeOn(AndroidSchedulers.mainThread())
                .replay();

        mAddedExecutionObservableSubject.onNext(connection);
        connection.connect();
        return connection;
    } catch (Exception e) {
        e.printStackTrace();
        return Observable.error(e);
    }
}