简体   繁体   中英

Inter page communication

In my iOS project I have three pages A, B, C

The app navigates from A --> B --> C.

Can I publish an event on A which would be received on page B and C, if those pages have subscribed to that event, but are not shown yet?

If you are on A and B and C haven't been shown yet, they can't have active subscriptions to any events. Hence, they will not receive the events.

Also you can't rely on this pattern if you want this to work on Android for instance.

Instead I would consider using a Service, which is a simple resolvable singleton, where you can store stuff, and let the ViewModels have that service injected in the ctor.

Something like this:

public interface IMyService
{
    string Data { get; set; }
}

public class MyService : IMyService
{
    public string Data { get; set; }
}

Then in your ViewModel for view A:

public class AViewModel : MvxViewModel
{
    public AViewModel(IMyService service)
    {
        GoToBCommand = new MvxCommand(() => {
            // set data before navigating
            service.Data = SomeData;
            ShowViewModel<BViewModel>();
        });
    }

    public ICommand GoToBCommand { get; }
}

ViewModel for View B:

public class BViewModel : MvxViewModel
{
    private readonly IMyService _service;
    public BViewModel(IMyService service)
    {
        _service = service;
    }

    public void Init()
    {
        // read data on navigation to B
        var data = _service.Data;
    }
}

Alternatively if you are only passing small values such as an Id, you could use request parameters:

ShowViewModel<BViewModel>(new { id = SomeProperty });

Then in your VM:

public void Init(string id)
{
    // do stuff with id
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM