# ajanuw-react-rxservice

> react service is a react state manager

Latest version **1.6.1** (published 2021-11-12) · MIT license · 0 weekly downloads

## Install

```sh
npm install ajanuw-react-rxservice
pnpm add ajanuw-react-rxservice
yarn add ajanuw-react-rxservice
bun add ajanuw-react-rxservice
```

## Health

**Score 30/100 (F)** — status: abandoned.

Positive: has types; esm support; no vulnerabilities; high quality score.

Warnings: low downloads.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 1.6.1 |
| Published | 2021-11-12 |
| First published | 2021-09-07 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Dependencies | 0 |
| Unpacked size | 153.3 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 1 |
| Author | Ajanuw |
| Maintainers | ajanuw |
| Keywords | react-rxservice, react, rxjs, rx, react rxjs, react service, useService, RxService, Ajanuw |

## Links

- npm: https://www.npmjs.com/package/ajanuw-react-rxservice
- Repository: https://github.com/januwA/react-rxservice
- Issues: https://github.com/januwA/react-rxservice/issues
- npm.io page: https://npm.io/package/ajanuw-react-rxservice

## Alternatives

- [mobx-react](https://npm.io/package/mobx-react.md) — 2.8M weekly downloads
- [rc-tree](https://npm.io/package/rc-tree.md) — 2.6M weekly downloads
- [@react-oauth/google](https://npm.io/package/@react-oauth/google.md) — 1.3M weekly downloads
- [@wagmi/connectors](https://npm.io/package/@wagmi/connectors.md) — 877.0K weekly downloads
- [vee-validate](https://npm.io/package/vee-validate.md) — 836.4K weekly downloads

## Recent versions

- 1.6.1 (latest) — 2021-11-12
- 1.6.0 — 2021-10-22
- 1.5.1 — 2021-10-13
- 1.5.0 — 2021-10-13
- 1.4.0 — 2021-10-12
- 1.3.0 — 2021-10-11
- 1.2.0 — 2021-09-24
- 1.1.2 — 2021-09-24
- 1.1.1 — 2021-09-22
- 1.1.0 — 2021-09-21
- 1.0.7 — 2021-09-21
- 1.0.6 — 2021-09-20
- 1.0.5 — 2021-09-12
- 1.0.4 — 2021-09-12
- 1.0.3 — 2021-09-12
- … 15 more at https://npm.io/package/ajanuw-react-rxservice/versions

## README

## react-rxservice

Use dependency injection to create services, inspired by Angular

## Install
```sh
$ npm i ajanuw-react-rxservice
$ npm i rxjs
```

如果你想使用`constructor`依赖注入

```sh
$ npm i reflect-metadata
```

配置 `tsconfig.json`

```json
{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
  },
}
```

## 全局服务

### 创建全局服务
```ts
@Injectable()
class AppService {
  i = 0;
}
```

`@Injectable` 立即注册一个全局服务，当数据变化时通知订阅者

### 订阅全局服务
```tsx
export default memo(() => {
  const [as] = useService(AppService);

  return (
    <RxService
      builder={() => {
        return (
          <div>
            <p>{as.i}</p>
            <button onClick={() => as.i++}>change</button>
          </div>
        );
      }}
    />
  );
});
```

`RxService` 组件会自动订阅全局服务，收到响应时触发更新


## 局部服务(非全局服务)

### 创建局部服务

```ts
@Injectable({ global: false })
class PS implements ServiceProxy {
  i = 0;
  
  OnCreate() {}
  OnUpdate() {}
  OnDestroy() {}
}
```

使用`Injectable`时可以传入一些配置项，将`global`设置为`false`注册为局部服务，并且不会立即注册

提供了一些钩子函数，用于监听局部服务的生命周期


### 订阅局部服务

```tsx
export default memo(() => {
  const [ps] = useService(PS);

  return (
    <RxService
      services={[PS]}
      global={false}
      builder={() => {
        return (
          <div>
            <p>{ps.i}</p>
            <button onClick={() => ps.i++}>change</button>
          </div>
        );
      }}
    />
  );
});
```

使用`useService`时初始化局部服务

`RxService`的`services`属性用于添加局部服务，`global`设置为`fasle`将不会订阅全局服务，如果你需要局部服务并且也需要全局服务可以无视此选项

`RxService` 被销毁时，`services`中的所有局部服务也会自动销毁，销毁前会调用 `OnDestroy`

`OnCreate` 在组件渲染完成之前触发

## 其他问题

### 不想监听服务中的某个属性的变更?

1. 使用`@Ignore`装饰器

  ```ts
  @Injectable({ global: false })
  class PS implements ServiceProxy {

    @Ignore()
    ref_ = React.createRef<any>();
  }
  ```

   2. 使用`autoIgnore`配置选项，会自动无视以`_`结尾的属性
  ```ts
  @Injectable({ global: false, autoIgnore: true })
  class PS implements ServiceProxy {
    ref_ = React.createRef<any>();
  }
  ```

### 在服务中使用其它服务?

  1. 使用`constructor`依赖注入
  ```ts
  import "reflect-metadata";

  @Injectable()
  class UserinfoService {}

  @Injectable()
  class AppService {
    constructor(public readonly userinfo: UserinfoService) {}
  }
  ```

  2. 使用静态属性
  ```ts
  @Injectable()
  class UserinfoService {
    static ins: UserinfoService;
  }

  @Injectable()
  class AppService {
    userinfo = UserinfoService.ins;
    i = 0;
  }
  ```

  3. 使用`@Late`装饰器
  ```ts
  @Injectable({ id: "UserinfoService" })
  class UserinfoService {
    i = 0;
  }

  @Injectable()
  class AppService {
    @Late("UserinfoService")
    userinfo!: UserinfoService;

    @Late("AfterService")
    after!: any;
  }

  @Injectable({ id: "AfterService" })
  class AfterService {}
  ```

  `@Late`装饰器需要提供一个服务的唯一id，如果这个服务已经被初始化则会立即初始化属性(userinfo)，否则会一直等到服务初始化时才设置属性(after)

  4. 在组件中使用多个服务?
  ```ts
  @Injectable()
  class UserinfoService {}

  @Injectable()
  class AppService {}

  @Injectable({ global: false })
  class PS {}

  export default memo(() => {
    const [ps, as, us] = useService(PS, AppService, UserinfoService);
    return (
      <RxService
        services={[PS]}
        builder={() => {
          return <div></div>;
        }}
      />
    );
  });
  ```

### 使用上一次销毁的数据?

*只能在局部服务中在这样做!*

  ```ts
  @Injectable({ global: false })
  class PS implements ServiceProxy {
    i = 0;
    OnDestroy() {
      return true;
    }
  }
  ```

  如果在页面销毁时`i=10`，并且在`OnDestroy`钩子中返回`true`，那么下次重启这个服务时，数据不会被初始化而是继续使用上一次的数据，再次进入页面你会直接看到`i=10`而不是`i=0`

  **服务从第一次创建就一直存在于内存中,销毁只是一个状态,在销毁状态下所有的变更都不会通知订阅者**

  **当再次启动销毁状态的服务时，只是取消了销毁状态，数据的初始化取决于上一次`OnDestroy`钩子的返回值，如果返回`true`将继续使用以前的数据，否则会重新初始化一个实例，并创建一个新的代理然后触发`OnCreate`钩子**

### 改变数据时，不想通知订阅者？

  ```ts
  @Injectable()
  class PS {
    i = 0;

    add() {
      noreact(() => {
        this.i++
      })
    }
  }
  ```

  在`noreact`的钩子函数中，改变数据时不会通知订阅者


  作为装饰器使用也可以达到同样的效果
  ```ts
  @Injectable()
  class PS {
    i = 0;

    @noreact()
    add() {
      this.i++
    }
  }
  ```

### 监听属性的变更

1. `Watch` 装饰器,监听一个或多个属性的变更
```ts
class PS {
  i = 0;
  obj = { i: 0 }

  @Watch(['this.i', 'this.obj.i'])
  watch(newVal: number, oldVal: number, key: string) {
    console.log(key, newVal, oldVal);
  }
}
```

2. `AutoWatch` 自动监听属性变化

```ts
class PS implements ServiceProxy {
  i = 0;
  j = 0;

  @AutoWatch()
  watch() {
    this.j = this.i * 2
  }
}
```

### 会自动代理哪些对象?

- `Array`
- `[object Object]`
- `[object Set]`
- `[object Map]`
- `[object WeakMap]`


## Run test
```sh
$ npm start
$ npm t
```

---
_Source: https://npm.io/package/ajanuw-react-rxservice · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
