add useObserved hook

This commit is contained in:
shilangyu 2020-09-30 01:19:44 +02:00
parent af7cb62fac
commit d3f0dd3fd4
1 changed files with 20 additions and 0 deletions

20
lib/hooks/observed.dart Normal file
View File

@ -0,0 +1,20 @@
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:mobx/mobx.dart';
/// Observes MobX observables in [fn] and returns the built value.
/// Behaves like a [useMemoized] with observables as a list of dependencies.
/// The returned value can be ignored for a `useEffect(() { autorun(fn); }, [])`
/// clone.
T useObserved<T>(T Function() fn) {
final returnValue = useState(useMemoized(fn));
useEffect(() {
final disposer = autorun((_) {
returnValue.value = fn();
});
return disposer;
}, []);
return returnValue.value;
}