Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Navigation in MVi #261

Open
littleGnAl opened this issue Jul 4, 2017 · 11 comments
Open

Navigation in MVi #261

littleGnAl opened this issue Jul 4, 2017 · 11 comments

Comments

@littleGnAl
Copy link

littleGnAl commented Jul 4, 2017

Consider such a demand:Click the button to post data to the server and then navigate to the other Activity when request success. I modified the ProductDetailsPresenter and ProductDetailsActivity to provide some test for me.

I add a testBtnIntent() method for the ProductDetailsView to handle a click intent.

public class ProductDetailsActivity extends MviActivity<ProductDetailsView, ProductDetailsPresenter>
    implements ProductDetailsView {

    @Override
    public Observable<Boolean> testBtnIntent() {
      return RxView.clicks(btnTest).share().map(it -> true);;
    }

    @Override public void render(ProductDetailsViewState state) {
    Timber.d("render " + state);

    if (state instanceof ProductDetailsViewState.LoadingState) {
      renderLoading();
    } else if (state instanceof ProductDetailsViewState.DataState) {
      renderData((ProductDetailsViewState.DataState) state);
    } else if (state instanceof ProductDetailsViewState.ErrorState) {
      renderError();
    } else if (state instanceof ProductDetailsViewState.TestViewState) {
      TestClickActivity.start(this);
    } else {
      throw new IllegalStateException("Unknown state " + state);
    }
  }
}

And then mergeWith the loadDetails method

 @Override protected void bindIntents() {
    ...
    Observable<ProductDetailsViewState> loadDetails =
        intent(ProductDetailsView::loadDetailsIntent)
            .doOnNext(productId -> Timber.d("intent: load details for product id = %s", productId))
            .flatMap(interactor::getDetails)
            .observeOn(AndroidSchedulers.mainThread());

    Observable<ProductDetailsViewState> clickTest =
        intent(ProductDetailsView::testBtnIntent)
        .map((aBoolean) ->  new ProductDetailsViewState.TestViewState());

    subscribeViewState(loadDetails.mergeWith(clickTest), ProductDetailsView::render);
  }

Because the viewStateBehaviorSubject will reemit the latest viewstate , so it will always reemit the clickTest when I go back the previous page and the TestClickActivity will open again and again, The expected should be to go back to the previous page without reemit the click event. Sorry
for my bad English. hope I can explanation of this. And can you give me some suggestion?

@sockeqwe
Copy link
Owner

sockeqwe commented Jul 4, 2017

We have some similar discussion about SnackBar here #255

However, I think navigation can be seen as "side effect" since it is not affecting (nor changing) the state for your current View. For Example the state of ProductDetailsActivity is not changed by navigation per se, right?

Navigation is "just" a side effect of a state change in ProductDetailsViewState. Side effects can be modeled in RxJava with doOnNext() operator.

I think something like this should work:
Assuming you have some class Navigator:

class Navigator {
    private final Activity activity;

    @Inject
    public Navigator(Activity activity){
        this.activity = activity;
    }

    public void navigateToTestActivity(){
          TestClickActivity.start(activity);
    }
}

Then you could inject the Navigator into ProductDetailsPresenter

class ProductDetailsPresenter extends MviBasePresenter<...> {

   private final Navigator navigator;
   
   @Inject
   public ProductDetailsPresenter(Navigator navigator){
         this.navigator = navigator;
    }


    @Override protected void bindIntents() {
    ...
    Observable<ProductDetailsViewState> loadDetails =
        intent(ProductDetailsView::loadDetailsIntent)
            .doOnNext(productId -> Timber.d("intent: load details for product id = %s", productId))
            .flatMap(interactor::getDetails)
            .observeOn(AndroidSchedulers.mainThread());

    Observable<ProductDetailsViewState> clickTest =
        intent(ProductDetailsView::testBtnIntent)
        .map((aBoolean) ->  new ProductDetailsViewState.TestViewState())
        .doOnNext( aBoolean -> navigator.navigateToTestActivity() ); // Navigation as side effect

    subscribeViewState(loadDetails.mergeWith(clickTest), ProductDetailsView::render);
  } 
}

Of course you have to keep in mind that Navigator might leak the Activity on config change (since presenter is kept during config change). I just wanted to illustrate a possible solution.

Does this makes sense?

@sockeqwe sockeqwe changed the title When merge the click event into the viewstateObservable Navigation in MVi Jul 4, 2017
@littleGnAl
Copy link
Author

@sockeqwe Thanks. It's a good solution, and maybe I can just pass the View to the Presenter just like MVP does, but I think whether have a more elegant way to do this?(Maybe like your discussion in #255

@andreiverdes
Copy link

Hi!
I chose to include navigation through the MVI pattern to be able to log every user action within the app.
I had the same problem above and couldn't just pass references to a Navigator or start activities from the Presenter because I keep the presentation layer in a separate project module.
My solution was to clear the navigation flags with another MVI intent triggered by onPause.
I know it's a bit dirty, I'm new to MVI, any feedback is welcomed! :D
PS: Great library!

Presenter.kt
...
override fun bindIntents() {
...
val clearViewStateIntent = intent { view -> view.clearNavigationIntent()}
                .map { LandingViewState() }
                .subscribeOn(Schedulers.io())

        val allIntents = Observable.merge(
                createViewIntent,
                loginIntent,
                signUpIntent,
                clearViewStateIntent
        ).observeOn(AndroidSchedulers.mainThread())

        subscribeViewState(allIntents, LandingContract.View::render)
}
Activity.kt
...
override fun onPause() {
        pauseSubject.onNext(true)
        super.onPause()
    }
override fun render(viewState: LandingContract.State) {
        when (true) {
            viewState.navigateToLoginScreen() -> SignInActivity.start(this)
            viewState.navigateToManageScreen() -> ManageActivity.start(this)
            viewState.navigateToSignUpScreen() -> SignUpActivity.start(this)
        }
    }

    override fun clearNavigationIntent(): Observable<LandingContract.Intent.ClearNavigationIntent> {
        return pauseSubject.map { LandingContract.Intent.ClearNavigationIntent() }
    }

@abyrnes
Copy link

abyrnes commented Feb 16, 2018

@sockeqwe How do you suggest handling navigation in the case where the next screen needs data that is in the view state?

@skykelsey
Copy link

I'm having the same problem. It seems the problem is caused by using view state to accomplish navigation as a side effect, as @sockeqwe mentioned. I am not a big fan of passing the Activity into the Presenter though, so I will try out the approach @andreiverdes outlined.

Would it be feasible to allow certain View States to be consumed instead of replacing the previous one?

@abyrnes
Copy link

abyrnes commented Apr 11, 2018

Would it be feasible to allow certain View States to be consumed instead of replacing the previous one?

@skykelsey For this I've been having a dummy state that gets emitted by navigation intents (I call it NoOp) and is just filtered out to avoid any unnecessary renderings:

val intent1 = intent(...)
val intent2 = intent(...)

val viewStateObservable = Observable.merge(intent1, intent1).filter { it !is NoOp } 
subscribeViewState(viewStateObservable, View::render)

This, however, doesn't solve the main problem at hand, for which I still haven't come up with an elegant solution, unfortunately. It doesn't seem like Mosby is well equipped to handle navigation in the presentation layer. So in the meantime I've implemented a base presenter that inherits from MviPresenter and hacks away at its implementation details to retrieve the previous view state, if it exists, and directly notify the view that a navigation event has occurred. This, combined with filtering out NoOp view states, has yet to cause me any issues.

@sockeqwe
Copy link
Owner

sockeqwe commented Apr 11, 2018 via email

@tschuchortdev
Copy link

I have figured out a simple pattern of how to do navigation properly

Any news on this? I couldn't find anything about it on your blog.

@sockeqwe
Copy link
Owner

My bad, I haven't had time to write a blog post or clean up my example repository ... Maybe next week ... sorry ...

@skykelsey
Copy link

Thanks @sockeqwe I'm interested as well when you find the time.

@sockeqwe
Copy link
Owner

sockeqwe commented May 6, 2018

Here you go:
http://hannesdorfmann.com/android/mosby3-mvi-8

Hope someone find it helpful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

6 participants