Reactive:使用observable刷新AccessToken

时间:2017-09-28 09:06:08

标签: c# system.reactive

我不太清楚如何调整this approach以生成动态计时器可观察数据。

具体而言,我有两种方法:

  1. GetAccessToken()
  2. RefreshAccessToken()
  3. 两者都返回OAuth2AccessTokenResponse

    public class OAuth2AccessTokenResponse
    {
        private string tokenType;
        private string accessToken;
        private int expiresIn;
        private string refreshToken;
        private int refreshtokenExpiresIn;
    }
    

    因此,我需要在expiresIn属性值之前刷新当前的accessstoken,以秒为单位。

    我试图采用我的方法,但是我没有能够得到任何意义:

    this.accessTokenObservable = Observable
        .Generate(
            this.GetAccessToken(),
            resp => true, //?????
            resp => resp, //?????
            resp => resp, //?????
            resp => TimeSpan.FromSeconds(this.RefreshAccessToken().ExpiresIn) //?????
        );
    

    Sequencially:

    1. response = this.GetAccessToken()
    2. response.ExpiresIn到期前 - > response = this.RefreshAccessToken()
    3. 转到2.
    4. GetAccessTokenRefreshAccessToken代码:

      internal OAuth2AccessTokenResponse GetAccessToken()
      {
          return new OAuth2AccessTokenResponse() {ExpiresIn = new Math.Random().Next(3,11)};
      }
      
      internal OAuth2AccessTokenResponse RefreshAccessToken()
      {
          return new OAuth2AccessTokenResponse() {ExpiresIn = new Math.Random().Next(3,11)};
      }
      

1 个答案:

答案 0 :(得分:1)

修复了一些编译错误之后,这似乎对我有用:

void Main()
{
    var accessTokenObservable = Observable
        .Generate(
            this.GetAccessToken(),
            atr => true,
            atr => this.RefreshAccessToken(),
            atr => atr,
            atr => TimeSpan.FromSeconds(atr.ExpiresIn)
        );

    accessTokenObservable.Subscribe(x => Console.WriteLine(x.ExpiresIn));
}

internal OAuth2AccessTokenResponse GetAccessToken()
{
    Console.WriteLine("!");
    return new OAuth2AccessTokenResponse() { ExpiresIn = rnd.Next(3, 11) };
}

internal OAuth2AccessTokenResponse RefreshAccessToken()
{
    Console.WriteLine("+");
    return new OAuth2AccessTokenResponse() { ExpiresIn = rnd.Next(3, 11) };
}

private Random rnd = new Random();

public class OAuth2AccessTokenResponse
{
    private string tokenType;
    private string accessToken;
    private int expiresIn;
    private string refreshToken;
    private int refreshtokenExpiresIn;

    public int ExpiresIn;
}

我得到这样的结果:

!
10
+
10
+
3
+
9
+