Skip to content

Instantly share code, notes, and snippets.

@rdlabo
Last active December 5, 2017 14:45
Show Gist options
  • Save rdlabo/82ecf251653c8f8bbc80e4a5f1c75bf3 to your computer and use it in GitHub Desktop.
Save rdlabo/82ecf251653c8f8bbc80e4a5f1c75bf3 to your computer and use it in GitHub Desktop.
dispatcher$.nextをPromiseっぽく使いたい

// Components側の処理で、dispatcher$.nextを実行するnextState$()メソッド完了時に、refresherの終了処理行いたい

export class Timeline {
    doRefresh(refresher) {
       this.stream.nextState$().then(
          data => refresher.complete();  // refresherの完了
        }
        }
       );
    }
}

// Providerはこんな感じです

@Injectable()
export class StreamTimelineProvider {

    private requester$ = new Subject<ActionState>();
    private dispatcher$ = new Subject<number>();
    private provider$ = new ReplaySubject<tweetInterface[]>(1);
    private isLoaded = true;

    constructor(
        public http: HttpClient,
    ){}

    public initialize() : void {
        this.requester$
            .switchMap((body) => {
                this.isLoaded = false;
                return this.http.post(RestURL + "v1/tweet/action", body)
            })
            .subscribe(() => {
                this.isLoaded = true;
                this.dispatcher$.next()
            });

        this.dispatcher$
            .switchMap((value:number) => {
                return this.getTimeline(value).toPromise()
            })
            .skipWhile(()=> !this.isLoaded)
            .subscribe(
                data  => this.provider$.next(data),
                error => this.provider$.error('つぶやきはありません')
            );
    }

    public destroy() : void {
        if(this.requester$)this.requester$.unsubscribe();
        if(this.provider$)this.provider$.unsubscribe();
        if(this.dispatcher$)this.dispatcher$.unsubscribe();
    }

    public getTimeline(page: number): Observable<tweetInterface[]>{
        let params = new HttpParams();
        params = params.append('page', String(page));

        return this.http.get<{
            timeline: tweetInterface[]
        }>(RestURL + "v1/tweet/timeline/",{ params: params })
            .map(res => {
                return res.timeline;
            });
    }

    public action_tweet(tweet_id, action, status) : void {
        const body = {
            tweet_id: tweet_id,
            action: action,
            status: status
        };
        this.requester$.next(body);
    }

    public getState$(): Observable<tweetInterface[]> {
        return this.provider$;
    }

    public nextState$() : void {
        this.dispatcher$.next(0);
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment