Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to finish current activity and launch a new activity Rx way?

I want to do the following but in Rx. The startActivity(intent) is guaranteed to be called since finish() is just an async call queued:

private fun launchNewActivity(){
  ...
  finish()
  startActivity(intent)
}

So in Rx way, I'm doing something like this, where both are packaged in their own observables (requirement):

private fun launchNewActivity(): Observable<Any>{
  ...
  return Observable.concat(
    Observable.just(finish())
    Observable.just(startActivity(intent))
    ...
  )
}

However, I'm worried in the Rx way, the activity could finish before startActivity is called. Would that happen?

like image 706
BeLambda Avatar asked Feb 28 '20 02:02

BeLambda


1 Answers

Actually you are calling it in a wrong order. You should call startActivity() first before calling finish(). Still, encapsulating this process inside an Observable might introduce an unexpected behavior, because startActivity() is supposed to be called on UI thread as it triggers UI animation/transition to another Activity.

What you want to do is to call both startActivity() and finish() inside onNext() or onComplete() callback. But in case you REALLY need to encapsulate it, you can follow these simple steps:

1. Create a method which handles Activity switching

private fun launchNewActivity() {
    startActivity(Intent())
    finish()
}

2. Encapsulate this method in Observable

Observable.fromCallable(this::launchNewActivity)

You will want to put above Observable inside a CompositeDisposable or a DisposableObserver.

like image 168
Harry Timothy Avatar answered Sep 22 '22 08:09

Harry Timothy