tdlib/
observer.rs

1// Copyright 2021 - developers of the `tdlib-rs` project.
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8use futures_channel::oneshot;
9use serde_json::Value;
10use std::collections::HashMap;
11use std::sync::RwLock;
12
13pub(super) struct Observer {
14    requests: RwLock<HashMap<u32, oneshot::Sender<Value>>>,
15}
16
17impl Observer {
18    pub fn new() -> Self {
19        Observer {
20            requests: RwLock::default(),
21        }
22    }
23
24    pub fn subscribe(&self, extra: u32) -> oneshot::Receiver<Value> {
25        let (sender, receiver) = oneshot::channel();
26        self.requests.write().unwrap().insert(extra, sender);
27        receiver
28    }
29
30    pub fn notify(&self, response: Value) {
31        let extra = response["@extra"].as_u64().unwrap() as u32;
32        match self.requests.write().unwrap().remove(&extra) {
33            Some(sender) => {
34                if sender.send(response).is_err() {
35                    log::warn!("Got a response of an unaccessible request");
36                }
37            }
38            None => {
39                log::warn!("Got a response of an unknown request");
40            }
41        }
42    }
43}