1 // Copyright (C) 2019 The Android Open Source Project 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 #ifndef IORAP_SRC_COMMON_RX_ASYNC_H_ 16 #define IORAP_SRC_COMMON_RX_ASYNC_H_ 17 18 #include "common/async_pool.h" 19 20 #include <rxcpp/rx.hpp> 21 22 namespace iorap::common { 23 24 // Helper functions to operate with rx chains asynchronously. 25 class RxAsync { 26 public: 27 // Subscribe to the observable on a new thread asynchronously. 28 // If no observe_on/subscribe_on is used, the chain will execute 29 // on that new thread. 30 // 31 // Returns the composite_subscription which can be used to 32 // unsubscribe from if we want to abort the chain early. 33 template <typename T, typename U> SubscribeAsync(AsyncPool & async_pool,T && observable,U && subscriber)34 static rxcpp::composite_subscription SubscribeAsync( 35 AsyncPool& async_pool, 36 T&& observable, 37 U&& subscriber) { 38 rxcpp::composite_subscription subscription; 39 40 async_pool.LaunchAsync([subscription, // safe copy: ref-counted 41 observable=std::forward<T>(observable), 42 subscriber=std::forward<U>(subscriber)]() mutable { 43 observable 44 .as_blocking() 45 .subscribe(subscription, 46 std::forward<decltype(subscriber)>(subscriber)); 47 }); 48 49 return subscription; 50 } 51 52 template <typename T, typename U, typename E> SubscribeAsync(AsyncPool & async_pool,T && observable,U && on_next,E && on_error)53 static rxcpp::composite_subscription SubscribeAsync( 54 AsyncPool& async_pool, 55 T&& observable, 56 U&& on_next, 57 E&& on_error) { 58 rxcpp::composite_subscription subscription; 59 60 async_pool.LaunchAsync([subscription, // safe copy: ref-counted 61 observable=std::forward<T>(observable), 62 on_next=std::forward<U>(on_next), 63 on_error=std::forward<E>(on_error)]() mutable { 64 observable 65 .as_blocking() 66 .subscribe(subscription, 67 std::forward<decltype(on_next)>(on_next), 68 std::forward<decltype(on_error)>(on_error)); 69 }); 70 71 return subscription; 72 } 73 }; 74 75 } // namespace iorap::common 76 77 #endif // IORAP_SRC_COMMON_RX_ASYNC_H_ 78