Created
September 17, 2019 13:41
-
-
Save ousado/83aee0f2fb507c94160f6576c196457a to your computer and use it in GitHub Desktop.
actix actors async response demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use actix::prelude::*; | |
use actix_rt::spawn; | |
use futures::{prelude::*,Future, future}; | |
use tokio_timer::Delay; | |
use std::time::{Duration,Instant}; | |
struct Ping(usize); | |
impl Message for Ping { | |
type Result = Result<usize,()>; | |
} | |
struct MyActor { | |
count: usize | |
} | |
impl Actor for MyActor { | |
type Context = Context<Self>; | |
} | |
impl Handler<Ping> for MyActor { | |
type Result = Response<usize,()>; | |
fn handle(&mut self, msg: Ping, _: &mut Context<Self>) -> Self::Result { | |
self.count += msg.0; | |
if self.count > 30 { | |
let count = self.count; | |
let fut = Delay::new(Instant::now() + Duration::from_secs(2) ) | |
.map(move |_| count ) | |
.map_err(|_| ()); | |
Response::fut( fut ) | |
} else if self.count > 20 { | |
Response::fut( Box::new(future::ok(self.count)) ) | |
} else { | |
Response::reply(Ok(self.count)) | |
} | |
} | |
} | |
fn show_result(t0:Instant, res: Result<usize,()>) -> usize { | |
if let Ok(res) = res { | |
println!("received res: {} at {:?}", res, Instant::now()-t0); | |
res | |
} else { | |
0 | |
} | |
} | |
fn main() -> std::io::Result<()> { | |
System::run(|| { | |
// start new actor | |
let addr = MyActor { count: 10 }.start(); | |
// send message and get future for result | |
let r1 = addr.send(Ping(10)); | |
let r2 = addr.send(Ping(10)); | |
let r3 = addr.send(Ping(10)); | |
let r4 = addr.send(Ping(10)); | |
let t0 = Instant::now(); | |
let show_result = move |res| show_result(t0, res); | |
spawn( | |
r1.map(show_result).join4(r2.map(show_result), r3.map(show_result), r4.map(show_result)) | |
.map(|res|{ | |
println!("RESULT: {:?}", res ); | |
System::current().stop(); | |
}).map_err(|_| ()) ); | |
}) | |
} | |
/* Output: | |
received res: 20 at 175.004µs | |
received res: 30 at 305.874µs | |
received res: 40 at 2.002365312s | |
received res: 50 at 2.002416s | |
RESULT: (20, 30, 40, 50) | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment