Search code examples
mvvmcross

return result from fragment hosted in activity (in MvvmCross)


I have fragment:

[MvxFragmentPresentation(ActivityHostViewModelType = typeof(MyHostActivityViewModel), FragmentContentId = Resource.Id.llContainer)]
[Register("views.MyFragmentView ")]
public class MyFragmentView : MvxFragment<MyFragmentViewModel>
{
...
}

This fragment is opened (in standalone host activity) by:

var result = await NavigationService.Navigate<MyFragmentViewModel, string, string>("sample input");

Now I try to return value from MyFragment by

class MyFragmentViewModel : MvxViewModel<string, string>
{
   void SomeMethod()
   {
      await NavigationService.Close(this, "my result");
   }
   ...
}

but above just closes fragment from host activity and host activity stays on the screen.

Do you have recommendations how to return value from MyFragment to caller? BTW. Maybe above should work but I spoiled sth in another place?

Thank you in advance!


Solution

  • I found workaround.
    When MyFragmentViewModel calls await NavigationService.Close(this, "my result") then caller of MyFragmentViewModel gets result back but host activity stays on the screen (covering caller view).

    As a workaround I manually close host activity:

    class MyFragmentViewModel : MvxViewModel<string, string>
    {
       public event Action ReturningResult;
    
       async void SomeMethod()
       {
          ReturningResult?.Invoke();
          await NavigationService.Close(this, "my result");
       });
       ...
    }
    
    [...]
    public class MyFragmentView : MvxFragment<MyFragmentViewModel>
    {
       public override void OnCreate(Bundle savedInstanceState)
       {
          base.OnCreate(savedInstanceState);
          ViewModel.ReturningResult += delegate
          {
             Activity.Finish();
          };
       }
       ...
    }