Skip to content

Use futures-await in the README examples #131

Closed
@seunlanlege

Description

@seunlanlege

Big thanks for this crate, also amazing work on the examples in the readme, i was able to get up and running with it very quickly.

But i believe the readme could be made better by using futures-await. since the goal is to demonstrate how to use the crate. The callbacks are very hard and are very error-prone (even the example isn't entirely correct see #130 ) to follow for someone who isn't very familiar with the futures crate

Proposal

#[macro_use] extern crate log;
extern crate lapin_futures as lapin;
extern crate futures_await as futures;
extern crate tokio;

use futures::prelude::*;
use futures::future::Future;
use futures::Stream;
use tokio::net::TcpStream;
use tokio::runtime::Runtime;
use lapin::client::ConnectionOptions;
use lapin::channel::{BasicPublishOptions,BasicProperties,QueueDeclareOptions};
use lapin::types::FieldTable;

fn main() {
  Runtime::new().unwrap().block_on(
    init().map_err(|err| error!("{:?}", err))
  ).expect("runtime exited with error");
}

#[async]
pub fn init() -> Result<(), std::io::Error> {
	let addr = "127.0.0.1:5672".parse().unwrap();

	let stream = await!(TcpStream::connect(&addr))?;
	// connect() returns a future of an AMQP Client
    // that resolves once the handshake is done
	let (client, heartbeat) = (await!(lapin::client::Client::connect(
		stream,
		ConnectionOptions::default()
	)))?;

	tokio::spawn(heartbeat.map_err(|_| ()));
	// create_channel returns a future that is resolved
    // once the channel is successfully created
	let channel = await!(client.create_channel())?;
	let id = channel.id;
	info!("created channel with id: {}", id);

	let queue =
		await!(channel.queue_declare("hello", QueueDeclareOptions::default(), FieldTable::new()))?;

	info!("channel {} declared queue {}", id, "hello");

	await!(channel.basic_publish(
		"",
		"hello",
		b"hello from tokio",
		BasicPublishOptions::default(),
		BasicProperties::default()
	))
}

I think this is much easier to understand and showcases the crate's api better.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions