Scope.kt 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. * MIT License
  3. *
  4. * Copyright (c) 2023 劉強東 https://github.com/liangjingkanji
  5. *
  6. * Permission is hereby granted, free of charge, to any person obtaining a copy
  7. * of this software and associated documentation files (the "Software"), to deal
  8. * in the Software without restriction, including without limitation the rights
  9. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. * copies of the Software, and to permit persons to whom the Software is
  11. * furnished to do so, subject to the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be included in all
  14. * copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  22. * SOFTWARE.
  23. */
  24. package androidx.lifecycle
  25. import com.drake.net.scope.AndroidScope
  26. import com.drake.net.scope.NetCoroutineScope
  27. import com.drake.net.time.Interval
  28. import kotlinx.coroutines.CoroutineDispatcher
  29. import kotlinx.coroutines.CoroutineScope
  30. import kotlinx.coroutines.Dispatchers
  31. /**
  32. * 在[ViewModel]被销毁时取消协程作用域
  33. */
  34. fun ViewModel.scopeLife(
  35. dispatcher: CoroutineDispatcher = Dispatchers.Main,
  36. block: suspend CoroutineScope.() -> Unit
  37. ): AndroidScope {
  38. val scope = AndroidScope(dispatcher = dispatcher).launch(block)
  39. addCloseable(scope)
  40. return scope
  41. }
  42. /**
  43. * 在[ViewModel]被销毁时取消协程作用域以及其中的网络请求
  44. * 具备网络错误全局处理功能, 其内部的网络请求会跟随其作用域的生命周期
  45. */
  46. fun ViewModel.scopeNetLife(
  47. dispatcher: CoroutineDispatcher = Dispatchers.Main,
  48. block: suspend CoroutineScope.() -> Unit
  49. ): NetCoroutineScope {
  50. val scope = NetCoroutineScope(dispatcher = dispatcher).launch(block)
  51. addCloseable(scope)
  52. return scope
  53. }
  54. /** 轮询器根据ViewModel生命周期自动取消 */
  55. fun Interval.life(viewModel: ViewModel) = apply {
  56. viewModel.addCloseable(this)
  57. }