简体   繁体   English

如何在rxjs中模仿“带有承诺的回调”功能参数?

[英]How to mimic a “callback with promise” function parameter in rxjs?

I'm an absolute rxjs beginner. 我是绝对的rxjs初学者。 For me to start learning to think in observables, I need to translate concepts through code examples. 为了让我开始学习观察性思维,我需要通过代码示例来翻译概念。 I feel like if I can see the code for this, I can start to do this on my own with other concepts. 我觉得如果可以看到它的代码,就可以与其他概念一起开始这样做。

I do NOT want to CONVERT a promise to an observable, I want to make a new implementation using Observable that can behave like a promise. 不想转换一个承诺可观察到的,我要让使用而观察到的新的实现,可以表现得像一个承诺。 How would I re-write the following using Observables? 如何使用Observables重写以下内容?

 constructor(){
    let makeMessage2 = function(){
        return new Promise(resolve, reject){
           setTimeout(()=>{
                  var r = Math.random();
                  resolve("message two plus random value: " + r );
           }, 1000);
        }
    }
    this.logMessageAndResultOfCallback("message one!", makeMessage2);
}
private sideEffect1:string = "";
private sideEffect2:string = "";

logMessageAndResultOfCallback( message1:string, callback:Function ){
    console.log(message1);
    this.sideEffect1 = message1;

    callback().then((message2)=>{
          console.log(message2);
          this.sideEffect2 = message2;
    }
}

I guess the part I don't understand is how to define the "callback" function, how to invoke it. 我猜我不了解的部分是如何定义“回调”函数,以及如何调用它。 I understand I would wait for the complete or emit handlers, like makeMessage2().subscribe(message2 => console.log(message2)); 我知道我会等待完整或发出处理程序,例如makeMessage2().subscribe(message2 => console.log(message2)); but I don't have any clue how to define makeMessage2 . 但我不知道如何定义makeMessage2

This may be totally clueless question, but I've read about 10 different intros to rxjs and this hasn't quite clicked. 这可能是毫无头绪的问题,但是我已经阅读了有关rxjs的10个不同的简介,而这还没有完全被点击。 I just need to map this scenario to observable pattern and I think I can understand it. 我只需要将此场景映射到可观察的模式,我想我就可以理解。

Basically, I want to define an observable function myObs() that does not "execute immediately" but "executes" whenever the someMethod(message:string,obs:Observable) is executed. 基本上,我想定义一个可观察函数myObs() ,它不会“立即执行”,而是在执行someMethod(message:string,obs:Observable)时“执行”。 When myObs is executed, it should do something ansynchronously within it (like get the result of a HTTP request) then set the next value, then fire a complete() so my observer defined in someMethod can handle the complete and do something with the result. 当执行myObs ,它应该在其中myObs执行某项操作(例如获取HTTP请求的结果),然后设置下一个值,然后触发complete(),以便我在someMethod定义的观察者可以处理完成并对结果进行某些处理。

Edit: I'm not concerned with the timer or native equivalents in rxjs, this is just to simulate any async action, like getting data from the server. 编辑:我不关心rxjs中的计时器或本机等效项,这只是为了模拟任何异步操作,例如从服务器获取数据。

The code that you wrote and want to 'translate' to observables probably would not work. 您编写并想要“翻译”为可观察对象的代码可能无法正常工作。 callback is a promise, not a function, so you can't write callback() . callback是一个承诺,而不是一个函数,因此您不能编写callback()

Did you try this introduction too? 您是否也尝试过此介绍 It worked for many people. 它为许多人工作。

To answer your question, you could write 要回答您的问题,您可以写

Rx.Observable.of(""message one!", "message two!")
  .map(console.log.bind(console)) // would be better to use `do` operator actually, for semantic reasons, but that works the same here
  .subscribe(noop, noop, noop)

or 要么

Rx.Observable.of(""message one!", "message two!")
  .subscribe(console.log.bind(console), noop, noop)

where noop is a function that does not do anything, ie function noop(){} 其中noop是不执行任何noop的函数,即function noop(){}

In short, your stream emits data, that data flow through a series of operators, and the data flow is started by .subscribe . 简而言之,您的流发出数据,该数据流通过一系列运算符,并且数据流由.subscribe启动。 In your case, you have nothing interesting to do on subscription, because all you do is logging. 对于您的情况,您对订阅没有任何兴趣,因为您所做的只是日志记录。

Rxjs Streams are in fact callback-based under the hood. Rxjs Streams实际上是基于后台的回调。 You want to check this answer to understand it. 您想查看此答案以了解它。

I solved it with help from this guide. 我在指南的帮助下解决了该问题

import {Observable} from 'rxjs';
var makeMessage2 = Observable.create(observer => {
  // Yield a single value and complete
  setTimeout(function(){
     let r = Math.random();
     observer.next("message two plus random value: " + r );
     observer.complete();
  }, 1000);
  return () => console.log('disposed')
});
logMessageAndResultOfCallback( "some message one", makeMessage2);


logMessageAndResultOfCallback( message1:string, callback:Observeable ){
    console.log(message1);
    this.sideEffect1 = message1;

    var subscription = callback.subscribe(
       (value)=>{this.sideEffect2 = value;},
       (e) =>{ console.log('onError: %s', e)},
       () => {console.log(this.sideEffect2);});
      subscription.dispose();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM