Parcourir la source

修复ViewModel作用域复用问题

drake il y a 3 ans
Parent
commit
90a5993b9a

+ 4 - 9
net/src/main/java/androidx/lifecycle/Scope.kt

@@ -22,9 +22,6 @@ import kotlinx.coroutines.CoroutineDispatcher
 import kotlinx.coroutines.CoroutineScope
 import kotlinx.coroutines.Dispatchers
 
-
-private const val JOB_KEY = "com.drake.net.view-model"
-
 /**
  * 在[ViewModel]被销毁时取消协程作用域
  */
@@ -32,9 +29,8 @@ fun ViewModel.scopeLife(
     dispatcher: CoroutineDispatcher = Dispatchers.Main,
     block: suspend CoroutineScope.() -> Unit
 ): AndroidScope {
-    val scope: AndroidScope? = this.getTag(JOB_KEY)
-    if (scope != null) return scope
-    return setTagIfAbsent(JOB_KEY, AndroidScope(dispatcher = dispatcher).launch(block))
+    val scope = AndroidScope(dispatcher = dispatcher).launch(block)
+    return setTagIfAbsent(scope.toString(), scope)
 }
 
 /**
@@ -45,7 +41,6 @@ fun ViewModel.scopeNetLife(
     dispatcher: CoroutineDispatcher = Dispatchers.Main,
     block: suspend CoroutineScope.() -> Unit
 ): NetCoroutineScope {
-    val scope: NetCoroutineScope? = this.getTag(JOB_KEY)
-    if (scope != null) return scope
-    return setTagIfAbsent(JOB_KEY, NetCoroutineScope(dispatcher = dispatcher).launch(block))
+    val scope = NetCoroutineScope(dispatcher = dispatcher).launch(block)
+    return setTagIfAbsent(scope.toString(), scope)
 }

+ 1 - 2
sample/src/main/java/com/drake/net/sample/ui/fragment/ViewModelRequestFragment.kt

@@ -12,8 +12,7 @@ import kotlinx.android.synthetic.main.fragment_view_model_request.*
 
 class ViewModelRequestFragment : Fragment(R.layout.fragment_view_model_request) {
 
-
-    val userViewModel: UserViewModel by viewModels() // 创建ViewModel
+    private val userViewModel: UserViewModel by viewModels() // 创建ViewModel
 
     override fun onViewCreated(view: View, savedInstanceState: Bundle?) {