如何在不阻塞的情况下从 Flux 获取列表? [英] How to get a List from Flux without blocking?

查看:63
本文介绍了如何在不阻塞的情况下从 Flux 获取列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回通量的存储库,并希望将结果设置为另一个需要列表的对象.有没有其他方法可以将结果作为列表而不阻塞?

I have a repository that returns a flux and wanted to set the result to another object which is expecting a list. Is there any other way to get the results as a list without blocking?

块正在工作,但需要很长时间.

The block is working but it is taking long time.

public class FluxToListTest {

    @Autowired PostRepository postRepository;

    public void setUserPosts(User user) {
      user.setPostList(postRepository.findAllByOrderId(user.getId()).collectList().block());
  }
}


interface PostRepository {

    Flux<Post> findAllByOrderId(final UUID userId);
}


@Data
class User {
  UUID id;
  List<Post> postList;
}


class Post {
    UUID id;
    String content;
}

推荐答案

简而言之 - NO.您不需要从 Flux 中提取 List.如果您已经开始使用 Reactor Streams - 继续使用它.

In short - NO. You don't need to extract List from Flux. If you've started use Reactor Streams - stay with it.

试试这个代码:

public void setUserPosts(User user) {
    postRepository.findAllByOrderId(user.getId())
        .collectList()
        .doOnNext(user::setPostList)// (1)
        .subscribe();               // (2) 
}  

  1. 如果您设置操作阻塞,请使用publishOn/subscribeOn 以避免阻塞所有流.
  2. 它开始你的流表演
  1. if you set operation is blocking please use publishOn/subscribeOn to avoid blocking for the all stream.
  2. it starts your stream performing

这篇关于如何在不阻塞的情况下从 Flux 获取列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆