aldanor / reactive-rs

Streams and broadcasts: functional reactive programming in Rust.
MIT License
35 stars 3 forks source link

lifetime conflict for a simple map #3

Open M-Adoo opened 5 years ago

M-Adoo commented 5 years ago

I try to map a trait object to downcast to another type, in the map operator. I don't know can how i do it in ractive-rs, just below simple demo will complain lifetime conflict. how can I return a reference in map? Should the observer callback accept a type is better than a reference ?

  #[test]
  fn test_stream() {
    let quotes = SimpleBroadcast::new();
    quotes
      .map(|e: &i32| e)
      .subscribe_ctx(|ctx, e| println!("recieve {}", e));

    quotes.send(1);
  }
aldanor commented 5 years ago
  1. In this case you have to dereference e, otherwise you're sending a reference (with a lifetime) down the pipeline.
  2. If you carefully read the example in the readme, it shows that you should use .clone() - because otherwise the broadcast would be moved and you won't be able to send to it.

So a correct example is (unless you want to do something else):

  #[test]
  fn test_stream() {
    let quotes = SimpleBroadcast::new();
    quotes
      .clone()
      .map(|e: &i32| *e)
      .subscribe_ctx(|ctx, e| println!("receive {}", e));

    quotes.send(1);
  }
M-Adoo commented 5 years ago

thx for your response. But when a type is not impl Copy, I can't direct dereference e.

aldanor commented 5 years ago

thx for your response. But when a type is not impl Copy, I can't direct dereference e.

But if the type implements Clone, you can clone it?

Otherwise, you will probably have to deal with RefCell and Rc, depending on your exact situation.