Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using a stream after the `for` loop #17

Closed
alexcrichton opened this Issue Sep 3, 2017 · 5 comments

Comments

Projects
None yet
3 participants
@alexcrichton
Copy link
Owner

alexcrichton commented Sep 3, 2017

Right now #[async] for will consume its stream argument (like for loops and iterators). Unlike iterators, however, there's not a great way to consume only half the stream and then continue using it afterwards (for example to break out early or reclaim resources).

With for loops you've got:

while let Some(x) = iter.next() {
    // ...
}

but there's not quite the same for streams!

@Arnavion

This comment has been minimized.

Copy link

Arnavion commented Sep 9, 2017

The user can just give a &mut reference to their stream to the for-loop, no? &mut Stream also impls Stream

@alexcrichton

This comment has been minimized.

Copy link
Owner Author

alexcrichton commented Sep 10, 2017

Unfortunately right now due to borrowing restrictions in generators that won't work :(

@Arnavion

This comment has been minimized.

Copy link

Arnavion commented Sep 10, 2017

Ah, you're right.

I guess then the current workaround is to manually loop over Stream::into_future() and bring the stream out of the loop.

fn foo<'a, S: Stream<Item = i32, Error = &'static str> + 'a>(mut s: S) -> impl Future<Item = (), Error = &'static str> + 'a {
	::async_block! {
		loop {
			match ::await!(s.into_future()) {
				Ok((Some(i), rest)) => {
					assert_eq!(i, 5);
					s = rest;

					// Only consume the first element.
					break;
				},

				Ok((None, rest)) | Err((_, rest)) => {
					s = rest;
					break;
				},
			}
		}

		assert_eq!(s.poll(), Ok(Async::Ready(Some(6))));

		Ok(())
	}
}
@alexcrichton

This comment has been minimized.

Copy link
Owner Author

alexcrichton commented Sep 11, 2017

Yeah I'd just hope we could get it a little more ergonomic than that :(

@withoutboats

This comment has been minimized.

Copy link
Collaborator

withoutboats commented Mar 11, 2018

I believe this is solved by await_item!?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.