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

2

5

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?

Loughlin answered 28/2, 2020 at 2:20 Comment(4)
try to call startActivity first than finishCensure
In our use case, we actually don't want to do that. There's an edge case, where calling finish() first has an advantage.Loughlin
What's the type returned by finish() and provided with the observable?Glaydsglaze
The actual call is something like finishActivityAction(), which calls finish() and returns an object "RoutingResult".Loughlin
I
8

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.

Iconology answered 1/3, 2020 at 18:54 Comment(0)
G
0

You can Start Your Next Activity Before Finish this Actvity.

First start your activity startactivity(Intent(this,NextActivity::Class.java) and after call finish() it work as finish your current activity.

here you can find code:

public fun startNewActivity(){
 startActivity(Intent(this,NewActivity::Class.java))
 finish()
}
Guaranty answered 6/3, 2020 at 17:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.