异步闪亮编程-建立一个基本示例

时间:2018-10-17 21:41:04

标签: r shiny

作为练习,我修改了默认的“老忠实间歇泉数据”应用程序以合并异步编程。但是,基于我对异步编程的理解,它的行为不能满足我的期望,我怀疑这是我的一个基本误会。

在这里,应用程序将创建2个相同的绘图输出。一个比另一个花费更长的时间,但是设置为异步工作,另一个则很快。

server.R

// First, define a simple event called UserWasCreated
public class UserWasCreated : Event
{
    public User User { get; private set; }

    public UserWasCreated(User user)
    {
        User = user;
    }
}

// Listener Example 1, Now we have a listener that would listen for when a user is added 
// This listener would simply send a welcome email to the new user
public class SendWelcomeEmail : Listener<UserWasCreated>
{
    public void Handle(UserWasCreated _event)
    {
        // here we can send an to the event.User....
    }
}

// Listener Example 2, Now we have a listener that would listen for when a user is added 
// This listener would simply sign up the user for an orientation
public class ScheduleOrientation : Listener<UserWasCreated>
{
    public void Handle(UserWasCreated _event)
    {
        // here we can schedule the orientation
    }
}

// In the controller we make announcement that the event took place
public UsersController : Controller
{   
    private IUserMapper UserMapper;
    private IAnnouncer Announcer;
  private IUserService UserService;

    public UsersController(IUserMapper userMapper, IAnnouncer announcer, IUserService userService)
    {
        UserMapper = userMapper;
        Announcer = announcer;
         UserService = userService;
    }

    ...

    [HttpPost, ValidateAntiForgeryToken]
    public ActionResult Create(CreateUserViewModel viewModel)
    {
        if (ModelState.IsValid)
        {
            User user = UserMapper.Map(viewModel);

            UserService.Create(user);

            // Here we announce the the event UserWasCreated took place.
            Announcer.Announce(new UserWasCreated(user));
        }

        return View(viewModel);
    }
}

ui.R

library(future)
library(promises)
library(shiny)
plan(multisession)

function(input, output) {

    bins = reactive({
        future({
            print("I'm slow")
            Sys.sleep(10)
            faithful[, 2]
        }) %...>% 
        {seq(min(.), max(.), length.out = input$slow_bins + 1)}
    })

    output$slow_dist_plot <- renderPlot({
        bins() %...>%
        {hist(faithful[, 2], breaks = ., col = 'darkgray', border = 'white')}

    })

    output$fast_dist_plot = renderPlot({
        print("I'm fast")
        x    <-faithful[, 2] 
        bins = seq(min(x), max(x), length.out = input$fast_bins + 1)
        hist(x, breaks = bins, col = 'darkgray', border = 'white')
    })

}

基于我对主要来自this Rstudio帖子的异步编程的理解,如果两个用户在最初绘制两个图之后同时运行了此代码,则其中一个用户更改了慢速垃圾箱,其他用户应该可以随意使用快速垃圾箱,并可以在其他用户请求由新流程处理时获得即时绘图。

但是,当我实际在两个窗口中尝试该操作时,我看到只要更改慢速仓位,其他窗口就必须等待慢速仓位完成。这是怎么了?我的期望是错误的还是我设置错误?

1 个答案:

答案 0 :(得分:0)

问题中的预期行为是正确的。但是,在单核计算机上,使用multisession计划时,默认情况下将工作程序数量设置为1。做

plan(multisession,workers = 2)

将具有预期的行为。对于实际使用的应用程序,可能有必要提高数量。