How to handle async calls by using Flutter Riverpod StateNotifier

407 Views Asked by At

Which of the following ways is the proper approach to handle async calls using Riverpod in Flutter? Should I worry about the getStringResult asynchronous call when the controller is being disposed as I do in approach B? Or shouldn't worry about the async call, can I use the simple approach A?

Approach 'A'

class Controller extends StateNotifier<String> {
    final Repository repository;
    
    Controller(this.repository):super(null);
    
    startAsyncJob() async {
        state = await repository.getStringResult()
    }
}

Approach 'B' by using the StreamSubscription

class Controller extends StateNotifier<String> {
    final Repository repository;
    StreamSubsciption? sub;

    Controller(this.repository):super(null);
    
    startAsyncJob {
        sub?.cancel();
        sub = repository.getStringResult().asStream().listen(event) {
            state = event;
        });
    }

    @override
    dispose() {
        sub?.cancel()
        super.dispose()
    }
}

I am using Approach 'B' in my controllers but it seems overkill to me. Did I overthink the problem? Will the async calls be disposed automatically when the controller does dispose?

0

There are 0 best solutions below